簡體   English   中英

如何根據按鈕單擊更改圓圈的顏色

[英]How can I change the color of the circle based on button click

我想知道如何根據單擊的相關顏色更改圓形部分的顏色我寫了一個 function 但它不起作用。 有人能幫我嗎?

編寫了 Javascript 代碼來更改顏色。 在這里,我嘗試將圓圈的背景顏色更改為單擊按鈕的顏色,但我似乎無法找到訪問卡片的方法; 之前在 CSS 中設置了背景顏色。

另一個問題是在單擊時從跨度中提取顏色,以便將圓圈的顏色更改為該顏色。

 function productCardColorChange1() { document.getElementById('card').before.style.background = document.getElementById('color1').style.background; }
 //this is the css code.container.card { position: relative; width: 320px; height: 450px; background: #232323; border-radius: 20px; overflow: hidden; }.container.card: before{ content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: #9bdc28; clip-path:circle(150px at 80% 20%); transition: 1s; }
 <div class="container"> <div class="card" id="card"> <div class="imgBx" id="imgBx"> <img src = "shoes.png"> </div> <div class="contentBx"> <h2>Nike shoes</h2> <div class="size"> <h3>Size:</h3> <span>7</span> <span>8</span> <span>9</span> <span>10</span> </div> <div class="color"> <h3>Color:</h3> <span id="color1" onclick="productCardColorChange1()"></span> <span id="color2"></span> <span id="color3"></span> </div> <a href="#">Buy Now</a> </div> </div> </div>

如果您針對多個元素,則使用addEventListener會更有效。

 const colors = document.querySelectorAll('.color > span') colors.forEach(elm => { elm.addEventListener('click', function(event) { const bgColor = window.getComputedStyle(event.target).backgroundColor if(bgColor) { document.getElementById('card').style.backgroundColor = bgColor } }) })
 #card { background-color: grey; }.container.card { position: relative; width: 320px; height: 450px; background: #232323; border-radius: 20px; overflow: hidden; }.container.card: before{ content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: #9bdc28; clip-path:circle(150px at 80% 20%); transition: 1s; }.color { width: 100%; background-color: grey; }.color > h3 { margin: 0; }.color > span { display: inline-block; width: 30px; height: 30px; margin: 10px; background-color: grey; } #color1 { background-color: green; } #color2 { background-color: pink; } #color3 { background-color: yellow; }
 <div class="container"> <div class="card" id="card"> <div class="imgBx" id="imgBx"> <img src = "shoes.png"> </div> <div class="contentBx"> <h2>Nike shoes</h2> <div class="size"> <h3>Size:</h3> <span>7</span> <span>8</span> <span>9</span> <span>10</span> </div> <div class="color"> <h3>Color:</h3> <span id="color1"></span> <span id="color2"></span> <span id="color3"></span> </div> <a href="#">Buy Now</a> </div> </div> </div>

暫無
暫無

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

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