![](/img/trans.png)
[英]How to achieve slide effect with background image position change on-click of buttons
[英]JavaScript change background image on-click?
我正在尝试使用一些基本的 JS 函数来更改我的 HTML 文档上的正文背景。 我已将 function 设置为针对特定 ID,然后设置 style.background 标签,如果是当前背景图像,则将其设置为我指定的另一个,否则保持相同的图像。 我现在已经无数次尝试更改代码,但似乎仍然无法更改背景。 对此的任何帮助将不胜感激。
HTML:
<div class="bg-image"
style="background-image: url('./img/frankie.jpg');
height: 100vh" id="bacgr"> <!--SETS BACKGROUND using id tag to change w/ JS-->
<main role="main" class="container d-flex justify-content-center">
<div class="starter-template">
<h1>Bootstrap starter template</h1>
<p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
</div>
</main>
</div>
JS:
let myImage = document.getElementById('bacgr').style.backgroundImage; //have to target specific image(like an array ([0])), put inside div w/ id.
myImage.onclick = function() {
if(myImage === "url('./img/frankie.jpg')") {
myImage == "url('./img/jesus_mobile.jpg')";
} else {
myImage == "url('./img/frankie.jpg')";
}
}
尝试这个:
const el = document.getElementById('bacgr');
el.onclick = function() {
if(this.style.backgroundImage === "url('./img/frankie.jpg')") {
this.style.backgroundImage = "url('./img/jesus_mobile.jpg')";
} else {
this.style.backgroundImage = "url('./img/frankie.jpg')";
}
}
这是示例
您只更改 URL,但不会将其分配回 dom 元素。
const el = document.getElementById('bacgr'); let prev = 'url("https://images.unsplash.com/photo-1570215171323-4ec328f3f5fa")'; el.onclick = function() { el.style.backgroundImage = prev === el.style.backgroundImage? 'url("https://images.unsplash.com/photo-1583508915901-b5f84c1dcde1")': prev; }
<div class="bg-image" style="background-image: url('https://images.unsplash.com/photo-1570215171323-4ec328f3f5fa'); height: 100vh" id="bacgr"> <main role="main" class="container d-flex justify-content-center"> <div class="starter-template"> <h1>Bootstrap starter template</h1> <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p> </div> </main> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.