【问题标题】:Uncaught TypeError: scrollIntoView is not a function. Child element isn't showing [duplicate]未捕获的 TypeError:scrollIntoView 不是函数。子元素未显示[重复]
【发布时间】:2019-09-10 11:49:12
【问题描述】:

我对“scrollIntoView”有疑问。它目前不工作。我正在尝试使具有“活动”类的列表项元素可见。有一个具有固定高度的无序列表,其中包含多个元素。有些元素是不可见的,您必须滚动到它们。我正在尝试使用“scrollIntoView()”,但它不起作用。请帮帮我。

function _ScrollTopImageNav() {
    var imageElement = document.getElementsByClassName("active");
    imageElement.scrollIntoView({
        behavior: "smooth"
    });
}
ul {
  list-style: none;
  height: 150px;
  overflow-y: auto;
  margin: 30px;
}

ul > li {
  background-color: aqua;
  height: 30px;
  width: 30px;
  display: block;
}

ul > li + li {
  margin-top: 10px;
}

ul > li.active {
background-color: red;
<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li class="active"></li>
</ul>

<a href="#" onclick="_ScrollTopImageNav()"> show element</a>

【问题讨论】:

  • document.getElementsByClassName 返回(实时)HTMLCollection,而不是节点,因此 HTMLCollection 没有 scrollIntoView 方法,因为那是节点方法,而不是 HTMLCollection 方法。 ..如果您知道您只想要第一个(或唯一)这样的元素,请改用document.querySelector('.active') - 请注意active前面的.

标签: javascript html


【解决方案1】:

getElementsByClassName 返回数组,但你需要单个元素,使用它访问它

imageElement[0].scrollIntoView

另外,some browsers 似乎不支持 behavior: "smooth"

下面的工作演示

function _ScrollTopImageNav() {
  var imageElement = document.getElementsByClassName("active");
  imageElement[0].scrollIntoView();
}
  ul {
  list-style: none;
  height: 150px;
  overflow-y: auto;
  margin: 30px;
}

ul>li {
  background-color: aqua;
  height: 30px;
  width: 30px;
  display: block;
}

ul>li+li {
  margin-top: 10px;
}

ul>li.active {
  background-color: red;
<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li class="active"></li>
</ul>

<a href="#" onclick="_ScrollTopImageNav()"> show element</a>

【讨论】:

  • 不是数组,而是类数组对象。
猜你喜欢
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 2015-08-18
相关资源
最近更新 更多