Onclick - 更改元素的背景图像

单击照片会执行叠加/弹出照片。我想更改弹出照片的背景图像以匹配链接它的 < a > 的背景图像。这个问题已经被问过很多次了,但我无法拼凑出正常运行的代码。我也想避免使用任何包,如果可能的话,只使用 css 是理想的,比如


onclick="document.getElementById("photoEnlarged")style.backgroundImage = 'cardinal2'"

调用函数的 div:


    <div class="photoFrame">

        <a onclick="myFunction('cardinal2')" href="#photoEnlarged">

            <img class="imgBird" src="Cardinal1.jpg">

        </a>

    </div>

功能:


<script>

    function myFunction(newURL) {

        var x = document.getElementById("photoEnlarged");

        x.style.backgroundImage = newURL;

    };

</script>

正在更改的元素的 CSS:


#photoEnlarged { 

    height: 635px; 

    width: 850px; 

    margin: 0 auto;

    position: relative; 

    z-index: 10; 

    display: none; 

    background: url(Cardinal1.jpg);

    background-size: cover; 

    border-color: #FFFFFF;

    border-style: double;

    border-width: 5px;

}

本网页的目录:

http://img4.mukewang.com/60efdf100001d3ab05930236.jpg

达令说
浏览 223回答 3
3回答

守候你守候我

查看现有的 CSS:url(Cardinal1.jpg)现在看看你分配的值:cardinal2你错过了url()部分和文件扩展名。关于您的编辑:&nbsp;x.style.backgroundImage&nbsp;=&nbsp;URL(newURL);JavaScriptURL函数将创建一个新的 URL 对象。你不想那样。您需要一个在开始和结束处带有和的字符串。url()x.style.backgroundImage&nbsp;=&nbsp;"url("&nbsp;+&nbsp;newURL&nbsp;+&nbsp;")";

HUH函数

这是我最终使用的确切函数/调用:功能:<head>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; function changeImg(imgURL) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('photoEnlarged').style.backgroundImage = 'url(' + imgURL +' )';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></head>调用函数:&nbsp; &nbsp; <div class="photoFrame">&nbsp; &nbsp; &nbsp; &nbsp; <a onclick="changeImg('YellowCrownedNightHeron1.jpg')" href="#photoEnlarged">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img class="imgBird" src="YellowCrownedNightHeron1.jpg">&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; </div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript