CSS有滚动条选择器吗?仅针对具有可见滚动条的元素



我想只使用CSS来定位具有可见滚动条的元素。如果没有javascript,这可能吗?

例如,如果我有3个用overflow-y:auto设置样式的div,那么只有当它们的滚动条出现时,我如何更改它们的样式?

CSS不包括此选择。您需要使用JavaScript。

对于纯CSS,我对此表示怀疑,但它也不需要太多javascript代码,看看这个例子:

document.querySelectorAll('*').forEach(el => {
  if (el.offsetHeight > document.documentElement.offsetHeight) {
      console.log('I am higher than my father: ', el);
      el.classList.add('higher-class');
  }
});
.higher-class {
  color: red;
}
<div class="container" style="height:50px;">
  <div class="some-child"  style="height:100px;font-size: 5rem">
    Higher element
  </div>
</div>

检查

  • offsetHeight属性:
    • https://developer.mozilla.org/es/docs/Web/API/HTMLElement/offsetHeight
  • 和classList属性:
    • https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

没有javascript是不可能的

然而,当滚动条可见时,它只需要一行JS就可以打开CSS类:

el.classList.toggle("scrollbarOn", el.scrollHeight > el.clientHeight)

这里有一个演示:

//toggles a class on an element when the scrollbar is visible:
function updScrollClass(el) {
  return el.classList.toggle("scrollbarOn", el.scrollHeight > el.clientHeight)
}
//changes the height of myDiv every second:
setInterval(function(){
  var myDiv = document.getElementById('myDiv')
  myDiv.classList.toggle('tall')
  updScrollClass(myDiv)
},1000)
#myDiv{ 
  width:150px;
  height:200px;
  overflow:auto;
}
#myDiv.tall{
  height:300px;
}
.scrollbarOn{ 
  background:yellow;
}
<div id='myDiv' class='tall'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc convallis nisl in accumsan porta. Etiam in urna orci. Vestibulum elementum, velit ac vestibulum efficitur, est elit auctor massa, nec porta ante nunc eget tellus. Integer eu ligula felis. 
</div>

最新更新