css 如何在HTML中为内联JS使用三重引号

wkftcu5l  于 2023-05-02  发布在  其他
关注(0)|答案(2)|浏览(191)

我有一个页面,我不能使用<script></script>,我必须在HTML中放置内联JS。
我很难找到一个三重引号通过JS改变css background-image的URL,我已经使用单引号和双引号e。g的。

<div onmouseover='document.getElementById("anotherDiv").style.backgroundImage = "url("https://www.test.com/image.jpg")";"></div>

在这里我需要一个三引号来括起来:

url("walrus-assets.s3.amazonaws.com/img/20-test-1.jpg")

有什么想法吗

4jb9z9bj

4jb9z9bj1#

这里是一个片段,但正如其他人所说,更喜欢css并在script标签中创建一个侦听器来更改样式,如第二个片段或第三个片段(如果脚本在head标签中)。

<div id = "anotherDiv" style="width: 200px; height: 100px; background-color:#995500;"></div>
    <div onmouseover="document.getElementById('anotherDiv').style.backgroundImage='url(https://dummyimage.com/200x100/666666/fff)'" style="cursor: pointer;">mouse over to change the background and use an image.
    </div>

第二个片段:

let mOverDiv = document.getElementById("mOverDiv");
        let anotherDiv = document.getElementById("anotherDiv");
        mOverDiv.addEventListener("mouseover", changeStyle);
        function changeStyle(e){
            anotherDiv.style.backgroundImage='url(https://dummyimage.com/200x100/666666/fff)';
        }
#anotherDiv{
            width:200px;
            height:100px;
            background-color:#996600;
        }
        #mOverDiv{
            cursor:pointer;
        }
<div id = "anotherDiv"></div>
    <div id = "mOverDiv">text in div</div>

如果您的脚本是在head部分中声明的,请使用第三个代码段。因此,您需要等待内容加载完毕,然后才能分配'divs'标记和侦听器:

let mOverDiv;
        let anotherDiv;
        document.addEventListener("DOMContentLoaded",addListener);
        function addListener(e){
            mOverDiv = mOverDiv = document.getElementById("mOverDiv");
            anotherDiv = document.getElementById("anotherDiv");
            mOverDiv.addEventListener("mouseover", changeStyle);
        }
        function changeStyle(e){
            anotherDiv.style.backgroundImage='url(https://dummyimage.com/200x100/666666/fff)';
        }
#anotherDiv{
            width:200px;
            height:100px;
            background-color:#996600;
        }
        #mOverDiv{
            cursor:pointer;
        }
<div id = "anotherDiv"></div>
    <div id = "mOverDiv">text in div</div>
ssgvzors

ssgvzors2#

您不需要为url()添加引号,请执行以下操作

<div onmouseover="document.getElementById('anotherDiv').style.backgroundImage = 'url(https://www.test.com/image.jpg)'"></div>

相关问题