“悬停” CSS选择器中的代码停止工作

时间:2019-12-06 20:57:51

标签: javascript html css

我正在尝试在页面内创建一个小的交互式图像库,除此问题外,其他所有东西都工作正常:当我将鼠标悬停在图像上时,它们按预期更改了不透明度和大小,但是,单击其中的一个后,扩大它,当我再次将鼠标悬停在它们上时,什么也没有发生。

这是我的意思:

example

当前CSS:

#houseImages img {
    opacity: 0.7;
    margin: 1em;
    transition: 0.3s;
    width: 18em;
    height: 15em;
    border-radius: 3em;
    border-style: solid;
    border-width: 0.05em;
}

#houseImages img:hover {
    transform: scale(1.1);
    opacity: 1.0;
    cursor: pointer;
}

单击图像时正在使用的当前脚本:

"use strict";

function defaultSettings(imgElement)
{
    imgElement.style.position = "initial";
    imgElement.style.transform = "scale(1.0)";
    imgElement.style.opacity = "0.7";
}

function clickedSettings(imgElement)
{
    imgElement.style.position = "absolute";
    imgElement.style.transform = "scale(2.6)";
    imgElement.style.left = "40%";
    imgElement.style.top = "30%";
    imgElement.style.opacity = "1.0";
    imgElement.style.zIndex = "99";
}

function imageClicked(imgID)
{
    let img = document.getElementById("img" + imgID);
    let otherImages = document.querySelectorAll("#houseImages img:not(#img" + imgID + ")");
    let div = document.getElementById("houseImages");
    let previousCloseImageButton = document.querySelector("#houseImages button");

    // if another image was already clicked there's some cleanup to do
    if(previousCloseImageButton)
        previousCloseImageButton.remove();

    otherImages.forEach(image => defaultSettings(image));

    clickedSettings(img);

    let closeImageButton = document.createElement('button');
    closeImageButton.setAttribute("id","close");
    closeImageButton.setAttribute("onclick","notClicked(" + imgID + ")");
    closeImageButton.innerHTML = 'X';
    div.append(closeImageButton);
}

function notClicked(imgID)
{
    let img = document.getElementById("img" + imgID);
    let closeImageButton = document.querySelector("#houseImages button");

    defaultSettings(img);

    closeImageButton.remove();

}

1 个答案:

答案 0 :(得分:5)

defaultSettings(img);函数中调用notClicked(imgID)时,将直接在HTML img对象上设置样式属性,就好像您已经用HTML编写了<img style="opacity: 0.7">一样。在对象上设置的样式始终比从样式表生成的样式具有更高的优先级。实际上,为#houseImages img:hover定义的规则不会影响您的图像。 您需要做的是取消设置一个本地样式属性,以使样式表再次起作用:

function defaultSettings(imgElement)
{
    imgElement.style.position = "";
    imgElement.style.transform = "";
    imgElement.style.opacity = "";
}