簡體   English   中英

單擊彩色按鈕更改圖像

[英]Change image on click of colored button

我正在幫助一個朋友訪問他的網站,他希望能夠通過單擊某些彩色按鈕來更改圖像,我嘗試使用data-color並獲取屬性並進行檢查,但大多數情況下它不起作用,並且硬修復我創建了一組不好的代碼,我在其中檢查每種顏色的功能,我想知道是否有可能在一個功能中做到這一點,並且比我在atm哈哈上做起來更容易或更容易!

代碼:在這里,我要求用戶選擇一種顏色並檢查

<h2> kies een kleur</h2>
<a href='#' onclick='red()'><div class="red colorChoose" data-color = 'red'> 
</div></a>

在這里,我替換圖像:

<div class="imageLook"><img alt="image" id="imageReplace" 
src="image location"></div>

而對於Javascript

function red()
{   
    if (document.getElementsByTagName("div")[2].getAttribute("data-color") == "red" ){       
        document.getElementById("imageReplace").src="image location";
    }
}

js擺弄着代碼,它根本不起作用,所以我不知道這是否有很大幫助...對於為此問題付出了很多努力的人們,我們深表歉意。 非常感謝! https://jsfiddle.net/ft5b8w9a/

感謝您的所有幫助和反饋!

另一種選擇是使用文件名代替顏色名稱。

 var img = document.querySelector( 'img' ); var buttons = document.querySelectorAll( 'button' ); // Use an object as a dictionary to map a color to a filename. var basePath = 'path/to/img/'; // Add event listener is JS not in the HTML. for ( var i = 0, len = buttons.length; i < len; i++ ) { var btn = buttons[ i ]; btn.addEventListener( 'click', function ( e ) { var file = basePath + this.getAttribute( 'data-file' ); img.src = file; img.alt = file; } ); } 
 <img src="path/to/img/default.jpg" alt="path/to/img/default.jpg"> <h2>Colors</h2> <button data-file="apple.jpg">Red</button> <button data-file="cloud.jpg">White</button> <button data-file="sky.jpg">Blue</button> 

如果出於某種原因您確實想要顏色名稱,那么我可以創建一個“字典” ,將顏色選項映射到文件。

 var img = document.querySelector( 'img' ); var buttons = document.querySelectorAll( 'button' ); // Use an object as a dictionary to map a color to a filename. var basePath = 'path/to/img/'; var colorToFile = { 'red': 'apple.jpg', 'white': 'cloud.jpg', 'blue': 'sky.jpg' }; // Add event listener is JS not in the HTML. for ( var i = 0, len = buttons.length; i < len; i++ ) { var btn = buttons[ i ]; btn.addEventListener( 'click', function ( e ) { img.src = basePath + colorToFile[ this.getAttribute( 'data-color' ) ]; img.alt = basePath + colorToFile[ this.getAttribute( 'data-color' ) ]; } ); } 
 <img src="path/to/img/default.jpg" alt="path/to/img/default.jpg"> <h2>Colors</h2> <button data-color="red">Red</button> <button data-color="white">White</button> <button data-color="blue">Blue</button> 

總體而言,如果可以的話,我會避免在HTML中添加事件處理程序(即<a onclick="function()"> )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM