我只想在单击按钮时更改背景。但是,我无法使用变量 change
来获取 div test2
的背景并将其存储为变量。我知道这一点是因为警报
test2
的值显示未定义
。
我知道这似乎是一个简单的修复,但我实际上找不到解决方案。这只是一个简单的语法错误还是我遗漏了什么?
如果能解释一下为什么会发生这种情况,我们将不胜感激,谢谢。
var el = document.getElementById('test');
function changeBG() {
var change = document.getElementById('test2').background;
el.style.background = change;
}
#test {
background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
}
#test2 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
}
<div id="test"></div>
<button onclick="changeBG();">hi</button>
最佳答案
导致错误/ undefined variable 的原因有几个。首先,您的 html 中没有 id 为“test2”的元素。您仅将 css style 分配给 id 'test2'。只有一个 id 为“test”的 div。另一个问题是 HTML 元素没有“背景”属性。要更改背景,您需要使用“style”属性,如 document.getElementById('test2').style.background = "url(...)";
有多种方法可以解决此问题,下面是一种使用类的方法。
- 从 div id 中删除
background
属性并创建两个 类、background
和background2
。 - 在 html 中,将
background
添加到test
div 作为默认值 类(背景图像)。 - 使用
toggle()
方法将类交替分配给 分区。
由于原始类 background
已分配,因此它将被删除并添加 background2
。如果您只想更改背景一次,那么您只需重新分配类即可(请参阅注释行)。
注意:您不能将背景属性保留为原始 div 的 id css 的一部分并添加具有新背景的类的原因是因为 id 优先,并且将覆盖任何具有相同名称的类属性,除非 !important
添加到类属性值的末尾 (background: url(..) !important;
),但如果可能,应避免使用该方法。此外,如果重要的话,Internet Explorer 9 不支持 classList
属性。
var el = document.getElementById('test');
function changeBG() {
//to change the background once
//el.className = "background2";
el.classList.toggle('background');
el.classList.toggle('background2');
}
#test {
width: 200px;
height: 200px;
background-size: cover;
background-position: center;
}
.background{
background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
}
.background2 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
}
<div id="test" class ="background"></div>
<button onclick="changeBG();">hi</button>
关于javascript - 使用 javascript 选择背景样式 - 如何修复简单的语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47443358/