【问题标题】:Is it possible to select pseudo elements like scrollbars using jQuery?是否可以使用 jQuery 选择像滚动条这样的伪元素?
【发布时间】:2019-11-19 12:37:28
【问题描述】:

是否可以选择像这样的伪元素:

::-webkit-scrollbar
::-webkit-scrollbar-track
::-webkit-scrollbar-thumb

通过 jQuery?

#scroller {
  background: #fff;
  height: 300px;
  width: 400px;
  overflow: hidden;
  overflow-y: scroll;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="scroller">
  <p>
    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. 
  </p>
</div>

【问题讨论】:

  • 滚动条不是 web 元素 - 它们是 browser 元素。
  • 你到底想做什么,为什么需要它们?
  • 我猜这个问题是基于错误的假设,因此无法以目前的形式回答。我建议更详细地编辑问题。
  • 一般来说,JavaScript 无法访问以:: 为前缀的伪元素。它们只在 CSS 中有意义,让您为这些元素设置样式。
  • jQuery 不能“直接”访问伪元素,但您可以将类添加到具有伪元素的元素中以更改该伪元素。但是,这对您的情况没有用。

标签: javascript jquery css-selectors pseudo-element


【解决方案1】:

你可以“读取”伪元素的值,但是你不能改变它们,至少我发现了。

尝试设置属性值返回错误:

在“CSSStyleDeclaration”上执行“setProperty”失败:这些样式是计算出来的,因此“width”属性是只读的。

var width = window.getComputedStyle(
  document.querySelector('#scroller'), '::-webkit-scrollbar').getPropertyValue('width');

console.log('::-webkit-scrollbar width> ' + width);

$(document).on('click', function() {
  // window.getComputedStyle(document.querySelector('.element'), '::-webkit-scrollbar').setProperty('width', '8px');
  // returns "Failed to execute 'setProperty' on 'CSSStyleDeclaration': These styles are computed, and therefore the 'width' property is read-only."
});
#scroller {
  width: 300px;
  height: 300px;
  overflow-y: scroll;
  background: #eee;
}

#scroller::-webkit-scrollbar {
  width: 10px !important;
}


/* Track */
#scroller::-webkit-scrollbar-track {
  background: #eee !important;
}


/* Handle */
#scroller::-webkit-scrollbar-thumb {
  background: #555 !important;
}


/* Handle on hover */
#scroller::-webkit-scrollbar-thumb:hover {
  background: #777 !important;
}

#scroller p {
  height: 800px;
  width: 100%;
  background: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="scroller">
  <p>
  </p>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-25
    • 2021-06-04
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    相关资源
    最近更新 更多