所以我有三个按钮。我想通过单击按钮之一来更改横幅的背景图像。我试图通过下面提供的功能对其进行设置。它应该按id来使用按钮,并更改类标题的背景图像。我究竟做错了什么 ?如果它改变了一些东西,我也正在使用sass。这是代码:function changebackground() { button1.addEventListener('click', function() { document.getElementsByClassName('banner').style.bacgkroundImage = "url(".. / images / banner - img.png ")"; }) button2.addEventListener('click', function() { document.getElementsByClassName('banner').style.bacgkroundImage = "url(".. / images / banner - img2.png ")"; }) button3.addEventListener('click', function() { document.getElementsByClassName('banner').style.bacgkroundImage = "url(".. / images / banner - img3.png ")"; })}.banner { background-image: url("https://via.placeholder.com/150 "); background-repeat: no-repeat; background-size: cover; width: 100%; height: 570px; z-index: 1; padding-top: 50px; position: relative;}.banner .carousel { top: 50%; position: absolute;}.banner .carousel .button { height: 10px; width: 10px; border: 2px solid white; margin: 10px; border-radius: 9px; position: relative;}.banner .carousel .button .first { position: absolute; margin-top: 3px; margin-left: 3px; height: 4px; width: 4px; border-radius: 5px; background: #fea100;}.banner .banner-text { font-family: "Playfair Display"; font-weight: 700; position: absolute; color: #fff; left: 15%; top: 40%; z-index: 2;}}<div class="banner"> <div class="carousel"> <div class="button" id="button1"> <div class="first"></div> </div> <div class="button" id="button2"> <div class="second"></div> </div> <div class="button" id="button3"> <div class="third"></div> </div> </div> <div class="banner-text"> <h1>Test your fav dish</h1> <h2>from <span>luxury restaurent</span></h2> </div></div>
2 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
该函数document.getElementsByClassName('banner')返回一个数组,因此您无法应用样式属性
其次,您的代码中存在语法错误"url(".. / images / banner - img.png ")",更改为:"url('../images/banner-img.png')"
要解决第一个问题,请尝试以下操作:
var banners = document.getElementsByClassName('banner');
//The following code needs to be inside the first click function, change it for the other two clicks
var i = 0;
for(i = 0; i < banners.length; i++)
{
banners[i].style.backgroundImage = "url('../images/banner-img.png')";
}
最后,您必须致电changebackground()使其生效
添加回答
举报
0/150
提交
取消