gpt4 book ai didi

javascript - "hover"CSS 选择器内的代码停止工作

转载 作者:行者123 更新时间:2023-12-03 09:40:16 25 4
gpt4 key购买 nike

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

这就是我的意思:

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();

}

最佳答案

当您调用 defaultSettings(img);notClicked(imgID)函数,您直接在 HTML img 对象上设置样式属性,就好像您写了 <img style="opacity: 0.7">在 HTML 中。对象上设置的样式总是比样式表中的样式具有更高的优先级。实际上,为 #houseImages img:hover 定义的规则不能影响你的形象。
您需要做的是取消设置本地样式属性以让样式表再次工作:

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

关于javascript - "hover"CSS 选择器内的代码停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59220250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com