[英]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.