.onclick 相当于给对象添加了一个属性 属性值 是一个函数 一点击就会触
div.onclick = function (){
alert('你好')
}
onmouseover 鼠标移到某元素之上
div.onmouseover = function(){
'#ccc'十六进制的颜色值
div.style.background = '#ccc'
}
onmouseout 鼠标从某元素移开
div.onmouseout = function(){
div.style.background = 'none'
}
onmousedown 鼠标按钮被按下
div.onmousedown = function (){
alert('鼠标被按下,还没有松开的时候触发')
}
onmousedown 鼠标按钮抬起的时候触发
div.onmouseup = function (){
alert('鼠标抬起的时候触发')
}
获取属性
<style>
.div1{
width: 200px;
height: 2000px;
padding: 10px;
margin: 5px;
border: 2px solid #ccc;
}
.c{
width: 100px;
height: 100px;
background-color: blueviolet;
position: absolute;
top:30px;
left:30px;
}
</style>
</head>
<body>
<div class="div1">
<!-- <div class="c"></div> -->
</div>
<button onclick="getScroll()">获取滚动条顶部的距离</button>
<script>
let divDom = document.querySelector('div')
/* width 只是content的宽度 */
// window.getComputedStyle(divDom,null).width
/* offsetWidth = content 宽度 + 左右的padding + 左右的border */
// divDom.offsetWidth ;
// divDom.offsetHeight ;
/* clientWidth = content 宽度 + 左右的padding */
//divDom.clientWidth ;
// divDom.clientHeight;
/* 在正常文档流下 offsetLeft(13) = body的margin-left(8) + divDom的margin-left(5) */
/* 脱离文档流的情况下 offsetLeft(25) = divDom的left(20) + divDom的margin-left(5) */
// console.log(divDom.offsetLeft);
/* 在正常文档流下 offsetTop(8) = body的margin-top(8) */
/* 脱离文档流的情况下 offsetTop(15) = divDom的top(10) + divDom的margin-left(5) */
// console.log(divDom.offsetTop);
/* offsetParent 自己相对于谁(父元素)偏移 */
// console.log( divDom.offsetParent ); => body
// let c = document.getElementsByClassName('c')[0];
/* c是绝对定位 是相对于divDom偏移的 所以他的偏移父元素是divDom */
// console.log( c.offsetParent ); /* =>divDom */
/* offsetParent 如果子元素的父元素是已经定位(relative,absolute,fixed)的元素,
那么他的offsetParent就是已经定位的父元素
如果不是已经定位的元素,那么他的offsetParent就是body
*/
获取滚动条距离顶部的高度
function getScroll()
console.log( document.documentElement.scrollTop );
}
滚动条 滚动事件
document.onscroll = function (){
console.log( document.documentElement.scrollTop );
}