使用jQuery动态更改滚动条轨道颜色

3
我需要根据用户选择的颜色更改滚动条的颜色。我尝试使用jQuery完成此任务,但无法更改轨道颜色。 https://jsfiddle.net/hoxtzL6o/
$(document).ready(function(){
    $(".container").css("color","blue");
    //$(".container::-webkit-scrollbar-thumb").css("background-color","blue !important")
  $(".container::-webkit-scrollbar-thumb").attr('style','background-color:blue')
})

我尝试了CSS和style属性。


Javascript 无法访问伪选择器。 - Rory McCrossan
最好切换一个类,因为无论如何你都不能从js/jq中定位伪元素滚动条,它不是DOM的一部分。另一种方法是在样式表中添加特定规则,如果出于某种原因你不想在任何硬编码的CSS规则中管理它。例如:https://jsfiddle.net/hoxtzL6o/1/ - A. Wolff
我不应该使用样式表,这是我的难点。如果用户选择了某种颜色,滚动条的颜色也应该相应更改。 - Alaksandar Jesus Gene
@AlaksandarJesusGene 但是为什么不使用 document.styleSheets[0].addRule('.container::-webkit-scrollbar-thumb',"background-color:" + x + " !important"); 呢? - A. Wolff
1个回答

3
伪元素不在DOM流中。您可以使用jQuery或JS将样式表附加到文档头部。以下是jQuery代码:
var styles = "<style type='text/css'>.container::-webkit-scrollbar-thumb{background-color: blue}</style>";  

$(styles).appendTo('head');

编辑:刚刚看到了评论。你可以像这样做。代码演示

以下是附加的代码片段。

$(document).ready(function() {
    var color;
    var picker;
    var new_stylesheet;
    
    $('button').click(function getcolor(color, picker, new_stylesheet) {
      color = $(this).val();
      picker = ".outer::-webkit-scrollbar-thumb {background:" + color + ";}";
      new_stylesheet = "<style type='text/css' id='currentCSS'>" + picker + "</style>";

      //check if stylsheet exists          
      existingStylesheet = $("#currentCSS");
      if (existingStylesheet.length) {$(existingStylesheet).replaceWith(new_stylesheet);}
      else {$(new_stylesheet).appendTo('head');}
    });
});
.outer {height: 100px;width: 80%;overflow-y: scroll;border: 1px solid #ccc;}
.inner {height: 150px}
.outer::-webkit-scrollbar {width: 13px}
.outer::-webkit-scrollbar-track {background: #ccc;}
.outer::-webkit-scrollbar-thumb {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer"><div class="inner">scrollable area</div></div>
<button value="red">red by default</button>
<button value="blue">pick blue</button>
<button value="green">pick green</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接