如何使用Javascript将CSS添加到-webkit-slider-runnable-track

时间:2018-03-06 04:45:03

标签: javascript jquery html css

我正在尝试更改范围滑块较低的颜色取决于幻灯片。使用下面的代码。

<head>
</head>
<input type="range" min="1" max="100" step="1" value="15"id="myrange" class="myrange">

CSS:

input[type="range"] {
    width: 100%;
    height: 28px;
    -webkit-appearance: none;
    outline: none;
    border: 0; /*for firefox on android*/
    padding: 0 8px; /*for IE*/
    margin: 8px 0;
}

/*chrome and opera*/
input[type="range"]::-webkit-slider-runnable-track {

    height: 8px;
    border-radius: 4px;
    transition: 0.3s;
    background-image: -webkit-gradient(
        linear,
        left top,
        right top,
        color-stop(0.15, orange),
        color-stop(0.15, #C5C5C5)
    );
}

.myrange::-webkit-slider-runnable-track {
    background-image: -webkit-gradient(
        linear,
        left top,
        right top,
        color-stop(0.15, orange),
        color-stop(0.15, #C5C5C5)
    );
    height: 8px; /*trackHeight*/
    border-radius: 4px; /*trackHeight*/
    transition: 0.3s;
}

input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none;
    background: orange;
    width: 28px;
    height: 28px;
    border-radius: 50%;
    margin-top: -12px;
    cursor: pointer;
    border: 4px solid #fff; 
    transition: 0.3s;
}

的javascript:

var style = $("<style>", {type:"text/css"}).appendTo("head");

$(function() {
  $('input[type="range"]').on('input change', function() {

    var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));

     style.text('.myrange::-webkit-slider-runnable-track{background-image:-webkit-gradient(linear, left top, right top, ' + 'color-stop(' + val + ', orange), '+ 'color-stop(' + val + ', gray);}');

  });
});

我想在使用滑块时更新input[type="range"]::-webkit-slider-runnable-track的CSS。

我已就相同主题验证了上一篇文章how to call range::-webkit-slider-runnable-track?,并相应地编辑了我的代码。真的很感激,如果有人可以帮我识别代码问题

小提琴:https://jsfiddle.net/fwmscany/1/

1 个答案:

答案 0 :(得分:0)

现在正在运作。这是我对Javascript的更新

$(function() {
var style = $("<style>", {type:"text/css"}).appendTo("head");
  $('input[type="range"]').on('input change', function() {

    var val = ($(this).val() - $(this).attr('min')) / ($(this).attr('max') - $(this).attr('min'));
 $('<style type="text/css"></style>').text('input[type="range"]::-webkit-slider-runnable-track { background-image:-webkit-gradient(linear, left top, right top, color-stop('+val+', orange), color-stop('+val+', #C5C5C5));}').appendTo('head');


  });
});