2017-02-21 207 views
0

我试图从顶部获得div距离。我知道这听起来很容易,但让我解释一下。从顶部获取点击div距离

我有很多与同类.item divs,并不是所有的人都在距离顶部相同的距离。所以,当我尝试像

var $distanceItem = $('.item').position().top; 
alert($distanceItem); 

它显然返回相同的值,即使点击的元素是进一步下跌,因为它们共享相同的类。

我想知道是否可以从我点击的元素顶部的距离。我必须说我不能使用id's

非常感谢

+0

?你如何执行该代码?你需要'this'或'$(this)',但没有[mcve]一个有用的答案将是困难的 – j08691

回答

2

点击的元素绑定到this变量jQuery的单击事件的回调函数,所以$(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>

+0

非常感谢AVAVT,这是我的尝试,但它不适用于我,由于语法错误。我的错。再次感谢。 – tanaan

0

那么,既然有超过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); 
});