简体   繁体   English

使用带有 css 选择器的 Javascript 滚动

[英]Scrolling using Javascript with css selector

I have a little problem with scrolling pop-up window.我在滚动弹出窗口时遇到了一些问题。 I want to scroll popup which has div and some css code.我想滚动具有 div 和一些 css 代码的弹出窗口。 no ID or CLASS.没有 ID 或 CLASS。

HTML CSS Code HTML CSS 代码

<div style="height: 356px; overflow: hidden auto;">

JS Code i have Tried我试过的 JS 代码

var objDiv = document.getElementsByTagName("div");
objDiv[0].scrollTop = objDiv[0].scrollHeight;

same code works for classes and id's相同的代码适用于类和 ID

<div class="123">

JS: JS:

var objDiv = document.getElementsByClass("123");
objDiv[0].scrollTop = objDiv[0].scrollHeight;

It's an instagram like pop-up.这是一个类似弹出窗口的Instagram。 i want to scroll using div or css selector (or both same time) using JS code我想使用 JS 代码使用 div 或 css 选择器(或两者同时)滚动

Your code would work if there was only one div on the page.如果页面上只有一个 div,您的代码就可以工作。 It's likely that you might have other divs on the page and the div you're after might not be the first.您可能在页面上有其他 div,而您要查看的 div 可能不是第一个。

If you want to scroll all overflow divs on the page you could do something like this如果您想滚动页面上的所有溢出 div,您可以执行以下操作

var divs = document.getElementsByTagName("div");

for (let div of divs) {
  if (div.style.overflow.includes("auto")) {
    div.scrollTop = div.scrollHeight;
    // break if you only want the first match
    // break;
  }
}

If not you could try to locate the exact div using querySelector and specifying a parent (your popup) id or class name and selecting the child div.如果不是,您可以尝试使用querySelector并指定父(您的弹出窗口)ID 或类名并选择子 div 来定位确切的 div。

eg例如

document.querySelector("#popup_div_id div");

Solution based on your comments根据您的意见解决方案

 var div = document.querySelector("div[style='flex-direction: column;']"); div.scrollTop = div.scrollHeight;
 div { height: 100px; width: 200px; overflow: auto; }
 <div style="flex-direction: column;"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras in viverra justo. Praesent in eros eget dui accumsan accumsan et suscipit ante. Aenean nec eros dignissim, luctus magna quis, rutrum augue. </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM