用原生js写法优化以下代码 function dragMoveX(container) { var flag; var downX; var scrollLeft; //鼠标按下 $(document.body).on("mousedown", container, function (event) { console.log('mousedown') flag = true; downX = event.clientX; scrollLeft = $(this).scrollLeft(); }); //鼠标移动 $(document).on("mousemove", function (event) { console.log('mousemove',flag,event.clientX) if (flag) { var moveX = event.clientX; var scrollX = moveX - downX; // console.log("moveX" + moveX); // console.log("scrollX" + scrollX); if (scrollX < 0 && scrollLeft > 0) { $(container).scrollLeft(scrollLeft - scrollX) } else { $(container).scrollLeft(scrollLeft - scrollX) } } }); //鼠标释放 $(document).on("mouseup", function () { console.log('mouseup') flag = false; }); /** * 注意:与 mouseout 事件不同,mouseleave 事件只有在鼠标指针离开被选元素时被触发,mouseout 事件在鼠标指针离开任意子元素时也会被触发。参见页面底部演示实例。 * 所以:如果mouseout的子元素存在溢出,并添加了超出加滚动,那么刚进入也会触发该事件,所以这里就不能使用。 * */ //鼠标移出元素 $(container).on("mouseleave", function (event) { console.log('mouseleave',event.pageX,document.body.offsetWidth) // flag = false; if (event.pageX < 0 || event.pageX > document.body.offsetWidth) { console.log('在元素上移出') flag = false; } }); }
时间: 2024-02-14 16:09:12 浏览: 112
可以使用原生JS改写该代码,如下所示:
```
function dragMoveX(container) {
let flag;
let downX;
let scrollLeft;
const body = document.body;
const containerEl = document.querySelector(container);
containerEl.addEventListener("mousedown", function(event) {
console.log("mousedown");
flag = true;
downX = event.clientX;
scrollLeft = this.scrollLeft;
});
body.addEventListener("mousemove", function(event) {
console.log("mousemove", flag, event.clientX);
if (flag) {
const moveX = event.clientX;
const scrollX = moveX - downX;
if (scrollX < 0 && scrollLeft > 0) {
containerEl.scrollLeft = scrollLeft - scrollX;
} else {
containerEl.scrollLeft = scrollLeft - scrollX;
}
}
});
body.addEventListener("mouseup", function() {
console.log("mouseup");
flag = false;
});
containerEl.addEventListener("mouseleave", function(event) {
console.log("mouseleave", event.pageX, body.offsetWidth);
if (event.pageX < 0 || event.pageX > body.offsetWidth) {
console.log("在元素上移出");
flag = false;
}
});
}
```
使用原生JS来绑定事件,而不是使用jQuery可以减少代码的依赖和加载时间,提高代码的执行效率。
阅读全文