我在试着得到离top的div距离。我知道这听起来很简单,但让我给你解释一下。
我有许多具有相同类.item的div,并不是所有的div都离顶部相同的距离。所以,当我尝试像这样的东西时
var $distanceItem = $('.item').position().top;
alert($distanceItem);它显然返回相同的值,即使被单击的元素进一步向下,因为它们共享相同的类。
我想知道是否有可能得到我点击的元素顶部的距离。我必须说我不能使用id's。
非常感谢
发布于 2017-02-22 03:38:34
被单击的元素被绑定到jQuery的单击事件回调函数中的this变量,因此$(this).offset().top;将从顶部向您提供它的位置。查看此演示:
$('body').on('click', '.item', function(e){
var positionFromTop = $(this).offset().top;
$('#result').html('Clicked div position from top: ' + positionFromTop + 'px');
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div id="result"></div>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>
</div>
发布于 2017-02-22 03:41:03
因为有超过1个div具有相同的类,所以jQuery的.position()函数接受该类的第一个div并返回它的位置。这就是为什么你会得到相同的值。
为了获得被点击的元素的位置,你可以在点击处理程序中使用this变量,如下所示:
// when any div that has the class="item" is clicked, call the same function
$(".item").click(function() {
// same function is called for every click, but the magic behind ``this`` is that
// in the click event callback, it changes to the item that was clicked on
var $distanceItem = $(this).position().top;
alert($distanceItem);
});https://stackoverflow.com/questions/42376355
复制相似问题