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

时间:2016-09-01 08:36:11

标签: jquery html css

我需要根据用户选择的颜色更改滚动条颜色。我试图用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属性。

1 个答案:

答案 0 :(得分:1)

伪元素不在DOM流中。您可以使用jQuery或JS将样式表附加到文档头。这是jQuery

var styles = "<style type='text/css'>.container::-webkit-scrollbar-thumb{background-color: blue}</style>";  

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

修改:刚看到评论。你可以这样做。 Codepen Example

还附上

下面的代码段

$(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>

相关问题