【Web】0基础学Web—事件对象、事件委托(事件代理)——星级评论案例

事件对象

<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>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值