0基础学Web—事件对象、事件委托(事件代理)——星级评论案例 事件对象 关闭鼠标右键的点击事件 关闭鼠标滚轮的事件 点击的目标对象 点击鼠标的左键0 滚轮1 右键2 获得被点击的节点的名称 或取相对于浏览器左上角的距离(会受页面滚动条的影响) 获取相对于文档左上角的距离(不受滚动条的影响) 事件委托—星级评论案例
事件对象
< body> < button> 点击</ button>
</ body>
关闭鼠标右键的点击事件
< script> _button. addEventListener ( "contextmenu" , function ( event ) { event. preventDefault ( ) } )
</ script>
关闭鼠标滚轮的事件
< script> _button. addEventListener ( "mousedown" , function ( event ) { event. preventDefault ( ) console. log ( event. button) } )
</ script>
点击的目标对象
< script> _button. onclick = function ( event ) { console. log ( event. target) }
</ script>
点击鼠标的左键0 滚轮1 右键2
< script> _button. onclick = function ( event ) { console. log ( event. button) }
</ script>
获得被点击的节点的名称
< script> _button. onclick = function ( event ) { console. log ( event. target. nodeName) }
</ script>
或取相对于浏览器左上角的距离(会受页面滚动条的影响)
< script> _button. onclick = function ( event ) { console. log ( event. clientX, event. clientY) }
</ script>
获取相对于文档左上角的距离(不受滚动条的影响)
< script> _button. onclick = function ( event ) { console. log ( event. pageX, event. pageY) }
</ script>
事件委托—星级评论案例
< style> .active { color : red; }
</ style> < body> < div class = " wrapper" > < div class = " first" > < span class = " active" > ❤</ span> < span> ❤</ span> < span> ❤</ span> < span> ❤</ span> < span> ❤</ span> </ div> </ div> < script> let _first = document. querySelector ( '.first' ) let _spans = document. querySelectorAll ( 'span' ) _first. onclick = function ( event ) { let index = [ ... _spans] . indexOf ( event. target) console. log ( index) for ( const i in _spans) { if ( i <= index) { _spans[ i] . classList. add ( 'active' ) } else { if ( _spans[ i] . classList != undefined ) { _spans[ i] . classList. remove ( 'active' ) } } } } </ script>
</ body>