[英]jQuery click on border of a div
我有一个div,其中包含大量文本。 我的问题是,是否有可能检测到div边框上的点击?
我想要完成的是如果用户点击底部边框(使用CSS设置4px宽的样式),div会一直滚动到底部。 如果不添加更多标记,这是否可行?
你可以试试这个:
$('div').click(function(e){
if(e.offsetY >$(this).outerHeight() - 4){
alert('clicked on the bottom border!');
}
});
.outerHeight()
只返回内容的高度(包括边框)。 e.offsetY
返回相对于元素的单击Y. 注意关于outerHeight
,如果传递一个bool true
参数,它将在计算值中包含margin
,默认为false
,所以它只返回content height + padding + border
。
更新 :看起来FireFox有自己的行为方式。 您可以看到,单击时,将鼠标按住元素,知道相对于元素的单击点的坐标是非常自然和方便的 。 但看起来我们没有方便的方法在所谓的FireFox中获取坐标,因为e.offsetX
和e.offsetY
根本不起作用(没有值)。 相反,你必须使用pageX
和pageY
减去.offset().left
和.offset().top
分别获得相对于元素的坐标。
我从来没有尝试过,但我不明白为什么它不应该工作:
计算元素的高度。
计算底部边界
计算元素本身内部的偏移量,就像在这里一样
现在,您可以使用一些数学检查鼠标位置是否在底部边框内。
我不确定盒子尺寸是如何适应这一点的,但这就是我如何开始。
您的元素周围有一个包装器,并将填充设置为您想要检测的内容。
jQuery的
$("#border").click(function (e) { if(e.target !== e.currentTarget) return; console.log("border-clicked") });
#border { padding: 4px; background: blue; box-sizing: border-box; cursor: pointer; } .box{ height: 100px; width: 100%; background: white; cursor: default; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="border"> <div class="box"></div> </div>
香草JS
var border = document.getElementById("border"); border.onclick = function(e) { if(e.target !== e.currentTarget) return; console.log("border-clicked") }
#border { padding: 4px; background: blue; box-sizing: border-box; cursor: pointer; } .box{ height: 100px; width: 100%; background: white; cursor: default; }
<div id="border"> <div class="box"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.