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

标签 javascript html css

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

我在做什么:

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/

相关文章:

html - 保持段落标签中的多行均匀对齐

jQuery fadeIn 函数不起作用

css - 为什么 Microsoft Edge 忽略 td 宽度?

javascript - 调用函数而不传递参数meteor app

javascript - 遍历JSON对象构建JSTree

javascript - 传递表单数据快速 react redux

php - xml 集成 - 将 xml 发布到 url

html - 将我的屏幕尺寸更改为智能手机屏幕尺寸时无法将我的背景图像居中

html - CSS如何把标题放在边框前面?

css - 2 个 DIV 与 float :right 重叠