如何使用JavaScript和按钮更改图像的不透明度?

4

不改变任何HTML代码,我需要三个按钮,分别对应每个图像,当我点击第一个按钮时,我需要将第二和第三幅图像的透明度设置为0%,第一幅图片设置为100%,其他两个按钮同理。

body {
  font-family: Avenir, sans-serif;
}
h1 {
  text-align: center;
  font-weight: 100;
}
#works {
  display: flex;
}
#works figure {
  transition: 1s opacity;
}
#works figure img {
  width: 100%;
  margin-bottom: 1rem;
}
        

<!doctype html>
    <html lang=en>
    <head>
    <meta charset=utf-8>
    <title>Sculptors and Architects of the Italian Renaissance</title>

    </head>
    <body>
    <h1>Sculptors and Architects of the Italian Renaissance</h1>
    <div id="works">
        <figure data-artist="michelangelo">
        <img src="david.jpg" alt>
        <figcaption>Head of <i>David</i>, Michelangelo (c. 1501)</figcaption>
    </figure>

    <figure data-artist="donatello">
        <img src="david-plaster.jpg" alt>
        <figcaption>Detail from painted plaster replica of Donatello's bronze <i>David</i> (c. 1430)</figcaption>
    </figure>

    <figure data-artist="brunelleschi">
        <img src="florence-cathedral.jpg" alt>
        <figcaption>Dome of Florence Cathedral by Filippo Brunelleschi (1436)</figcaption>
        </figure>
    </div>

    <div id="controls">
    <button id="button">Michelangelo</button>
    <button id="button2">Donatello</button>
    <button id="button3">Brunelleschi</button>
    </div>
      <script>

        </script>
    </body>
    </html>

是否有没有更改HTML的原因? - Saeed Ludeen
是的,显然可以在不改变它的情况下实现。 - rubyre
1
需要做出一些改变。您需要通过将样式注入到引用元素的HTML中或更改element.style.opacity属性来更改元素的不透明度。 - Kyle Richardson
1个回答

0

进行了一些修改:

<button id="michelangelo">Michelangelo</button>
<button id="donatello">Donatello</button>
<button id="brunelleschi">Brunelleschi</button>

使用jQuery:

$('button').click(function(e){
    e.preventDefault();
    $('figure').style.opacity = '0';
    $(`figure[data-artist="${$(this).attr('id')}"`).style.opacity = '1';
});

1
注意:你需要在 head 中添加以下代码来引用 jQuery:<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script> - Saeed Ludeen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接