使用数据属性滚动到元素

使用数据属性滚动到元素

本文介绍了使用数据属性滚动到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我试图弄清楚如果元素与 ID 匹配而不是使用锚标记,我如何使用数据属性将元素滚动到特定元素.这是我的工作.

一旦用户单击按钮,它将显示内容并滚动到与数据属性匹配的特定元素.我似乎无法让它滚动

<div class="post" data-id="content-one">一贴

<div class="post" data-id="content-two">贴二

<div class="container-two"><div id="content-one" class="post-content" >内容一

<div id="content-two" class="post-content" >内容二

$(".container .post").on('click', function() {var data_id = $(this).data('id');$('.post-content').each(function() {var el = $(this);if (el.attr('id') == data_id)el.show();别的el.hide();});$('html, body').animate({滚动顶部:$(data_id).offset.top()}, '减缓');});

https://jsfiddle.net/clestcruz/vf4ufg6b/

解决方案

# 连接到 id 以形成正确的选择器.也使用 .offset().top 因为 offset()> 是一个函数,它返回一个包含元素当前位置的对象.然后我们可以使用 top 键访问它.

$('html, body').animate({scrollTop: $( '#' + data_id).offset().top}, '减缓');

演示

I'm trying to figure out how I can have the element scroll to a particular element using data-attributes if it matches the ID instead of using anchor tags. Here is what I'm working.

Once the user clicks on a button it will show the content and also scroll to that particular element that matches the data-attributes. I can't seem to make it scroll

<div class="container">
    <div class="post" data-id="content-one">
        post one
    </div>
    <div class="post" data-id="content-two">
        post two
    </div>
</div>
<div class="container-two">
    <div id="content-one" class="post-content" >
      content one
    </div>
    <div id="content-two" class="post-content" >
      content two
    </div>
</div>
$(".container .post").on('click', function() {
    var data_id = $(this).data('id');
    $('.post-content').each(function() {
        var el = $(this);
        if (el.attr('id') == data_id)
            el.show();
        else
            el.hide();
    });
    $('html, body').animate({
        scrollTop: $(data_id).offset.top()
    }, 'slow');
});

https://jsfiddle.net/clestcruz/vf4ufg6b/

解决方案

Concatenate a # to the id to make a proper selector. Also the use .offset().top because offset() is a function which returns an object which contains current position of the element. Then we can access it using the top key.

$('html, body').animate({
    scrollTop: $( '#' + data_id).offset().top
}, 'slow');

DEMO

这篇关于使用数据属性滚动到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:20