查找并滚动到元素

Find and scroll to element

本文关键字:元素 滚动 查找      更新时间:2023-09-26

大家好!我正在编写一个基于bootstrap3的板。有一个数据库充满了声音信息,我正在从中创建div。我想添加一个搜索栏,在页面中找到元素并滚动到它。我已经看了jquery.scrollTo或javascript,但我找不到如何做到这一点!

这是我想使用的搜索表单:

<form class="navbar-form navbar-left" role="search">
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Search">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>

这是身体的样子:

  echo "<div id='EPsound".$j."' name='".$name[$j]."' class='col-md-6'></br>"; //créer une div pchq son
            echo "<div class='sound center-block'>";
                echo "<img src=".$artwork[$j]." class='img-thumbnail center-block' />";
                echo "<span>$name[$j]</span>";
                echo "<i class='fa fa-play fa-3x play' onclick='$onclickplay'></i>";
                echo "<i class='fa fa-plus fa-3x plus' onclick='$onclickqueue'></i>";
            echo "</div>";
  echo "</div>";

非常感谢您的帮助!

JavaScript:

如果你正在寻找一个纯JavaScript解决方案,你可以使用

scrollIntoView()

方法。

要使用它,你需要一个你想应用它的"元素"。因此,你可以这样应用它:

document.getElementById("elementID").scrollIntoView();

您可以在此处查看:http://jsfiddle.net/yYq39/1/

这些方法只是使所述元素立即成为焦点。因此,从用户的角度来看,整体效果并不那么好!!!

JQuery:

如果你正在寻找一个平滑滚动到上述元素,你可以使用Jquery的ScrollTop函数:

你可以这样使用它:

$("#btnScroll").click(function() {
    $("html, body").animate({ scrollTop: $("#block2").offset().top }, 500);    
});

您可以在此处查看:http://jsfiddle.net/3ak6L/

希望这能有所帮助!!!

// Grab all the result containing the name
var list = $('.sound span'); // you should add a better scope
// Whenever user type in the input field...
$('.navbar-form input').on('keyup', function (e) {
   var regex = new RegExp(e.currentTarget.value, 'ig');
   // ...try to find if any element is matching typed text
   for (var i = 0, len = list.length; i < len; i += 1) {
     list[i].name.toLowerCase().match(regex) && list[i].scrollIntoView();
     break; // stop when found
   }
});