【问题标题】:get element id when scroll to it滚动到它时获取元素ID
【发布时间】:2013-03-07 03:59:41
【问题描述】:

我有一个在线阅读漫画的网站。

阅读页面的HTML是:

<div id="listimages">
<img src="abc1.jpg" id="image1" />
<img src="abc2.jpg" id="image2" />
<img src="abc3.jpg" id="image3" />
<img src="abc4.jpg" id="image4" />
</div>

我想获取滚动到的图像的 id。 例如,当我查看 img abc2.jpg 时,我想获取它的元素 id 是 #image2。

idnow = idnow_getted

请帮帮我,谢谢大家!

【问题讨论】:

标签: javascript jquery scroll element


【解决方案1】:

您可以比较窗口的滚动顶部和图像的顶部位置,以获取滚动到的图像的 id。

例如,

$(window).scroll(function() {

var winTop = $(this).scrollTop();
var $imgs = $('img');

$.each($imgs, function(item) {
    if($(item).position().top <= winTop)
         //get id here

});
});

【讨论】:

【解决方案2】:

可能有两种情况,您需要图像的 id 并进行进一步处理,

第一个场景您想在窗口滚动时执行某些操作。 在这种情况下,只需在滚动事件上添加一个处理程序。

$(window).scroll(function() {

    var windowTop = $(this).scrollTop(),
        image = $('#listimages').find('img').filter(function(){
            return $(this).offset().top < windowTop+100;
           //i am adding 100 in windowTop as we can consider the the image as cuurent image even if it is little bit below than top of window.
        });


            //now you can directly use image if you want to manipulate it.
            //if you want id you can get it by
          var id=image[0].id //or image.attr('id'); 

    });

第二个场景,如果你想在触发任何事件时执行一些操作。

function currentImg(){
            var windowTop = $(this).scrollTop(),
            image = $('#listimages').find('img').filter(function(){
                return $(this).offset().top < windowTop+100;
             });
           return image[0].id;

}

但请记住,添加诸如滚动、鼠标移动之类的事件会更频繁地执行,因此建议在您非常需要之前不要使用太多。

【讨论】:

    【解决方案3】:

    只需尝试以下方法,

    JavaScript 和 jQuery 部分:

    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
    $('#listimages img').mouseover(function() {
       alert(this.id);
    });
    });
    </script>
    

    HTML 部分:

    <div id="listimages">
    <img src="abc1.jpg" id="image1" />
    <img src="abc2.jpg" id="image2" />
    <img src="abc3.jpg" id="image3" />
    <img src="abc4.jpg" id="image4" />
    </div>
    

    我认为这可以帮助您解决问题。

    【讨论】:

    • 鼠标悬停与滚动不同。
    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 2017-07-18
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多