gpt4 book ai didi

javascript - 动态添加样式到 Vanilla js 中的元素不起作用

转载 作者:行者123 更新时间:2023-11-28 02:51:50 34 4
gpt4 key购买 nike

我正在尝试自定义范围类型输入的栏,但是由于某种原因我还没有弄清楚,背景图像没有被设置。

我在做什么:

var age = document.querySelector('#age');
var ageResult = document.querySelector('#age-result');
ageResult.textContent = age.value;
age.addEventListener('change', function(event) {
var value = (event.target.value - event.target.min) / (event.target.max - event.target.min);
this.style.backgroundImage = '-webkit-gradient(linear, left top, right top, '
+ 'color-stop(' + value + ', #e8972c), '
+ 'color-stop(' + value + ', #e6e6e6) '
+ ')';
if (event.target.tagName === 'INPUT') {
ageResult.textContent = event.target.value;
}
})

这是代码片段:

var age = document.querySelector('#age');
age.addEventListener('change', function(event) {
var value = (event.target.value - event.target.min) / (event.target.max - event.target.min);
this.style.backgroundImage = '-webkit-gradient(linear, left top, right top, '
+ 'color-stop(' + value + ', #e8972c), '
+ 'color-stop(' + value + ', #e6e6e6) '
+ ')';
})
input[type=range]{
-webkit-appearance: none;
/* fix for FF unable to apply focus style bug */
border: 1px solid white;
}
input[type=range]:focus {
outline: none;
}
input[type=range]:focus::-webkit-slider-runnable-track {
background: #ccc;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: none;
height: 30px;
width: 30px;
border-radius: 50%;
background: #ffffff;
margin-top: -11px;
background-image: linear-gradient(rgba(255,255,255,0),rgba(0,0,0,0.1));
box-shadow: 0 0 8px rgba(0,0,0,0.3);
}
input[type=range]::-webkit-slider-runnable-track {
height: 10px;
background: #dddddd;
border: none;
border-radius: 3px;
}
<input type="range" name="age" id="age" min="14" max="70" value="31">

你能看出我做错了什么吗?为什么没有设置 style.backgroundImage?我调试了一下,发现在那一行之后它是空的。

最佳答案

在 CSS 文件中设置 CSS 属性。如果您想通过脚本 (JavaScript) 以动态/编程方式更改某些内容,最好的办法是打开/关闭单独的 CSS 类来进行更改。换句话说,尽可能少地使用 JS 的 .style 方法。而是使用 JS 的 .classList

关于javascript - 动态添加样式到 Vanilla js 中的元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46633096/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com