我尝试使用 Javascript 实现 CSS3 转换,以便在鼠标未悬停时使图像变灰 <img>
并在鼠标位于其上时使用颜色进行渲染。
这是我的代码片段:
// Create container for image of simulation
var containerImage = document.createElement('div');
containerImage.className = 'wrap';
elementBodyContent.appendChild(containerImage);
// Create text for imageElement
var textElement = document.createElement('div');
textElement.className = 'text-over-image';
textElement.innerHTML = 'Click to raise simulation';
containerImage.appendChild(textElement);
// Create image of simulation
var imageElement = document.createElement('img');
imageElement.className = 'contrast';
imageElement.width = 700;
imageElement.height = 381;
imageElement.style.cursor = 'pointer'
imageElement.cursor = 'hand';
imageElement.src = 'http://ghujisl.com/Scene.png';
imageElement.onload = function() {
containerImage.insertBefore(imageElement, textElement);
};
和 CSS 相关的:
img.contrast
{
filter: contrast(0.3);
-webkit-filter: contrast(0.3);
-moz-filter: contrast(0.3);
-o-filter: contrast(0.3);
-ms-filter: contrast(0.3);
-webkit-transition: all 0.3s ease-in-out;
-moz-transition: all 0.3s ease-in-out;
-o-transition: all 0.3s ease-in-out;
-ms-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
img.contrast:hover
{
filter: contrast(1);
-webkit-filter: contrast(1);
-moz-filter: contrast(1);
-o-filter: contrast(1);
-ms-filter: contrast(1);
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1);
}
.wrap {
height:auto;
margin: auto;
text-align:center;
position:relative;
}
.text-over-image {
position: absolute;
margin: auto;
cursor: pointer;
top: 0;
left:0;
right:0;
bottom:0;
color:#fff;
height:100px;
}
但不幸的是,转换无法正常工作。一旦我出现在图像上,有时 contrast filter
被应用,有时不应用。
此外,当鼠标悬停在图像上时,如果我停止并重新开始移动鼠标,总是在图像上,开始图像渲染又回来了(我再次得到灰色图像,而鼠标仍在图像上)。
您可以在[以下链接][1] 上测试这种奇怪的行为。
我在 Firefox 52 和 Chrome 版本 57.0.2987.133 上进行了这些测试。
如果有人能看出哪里出了问题,告诉我就好了。
最佳答案
罪魁祸首是您的 .text-over-image
div。由于它绝对位于图像上方,因此无论何时将鼠标放在它上面,鼠标事件都会传输到该 div 而不是图像。
一个简单的解决方法是将其添加到您的 CSS 中:
.text-over-image{
pointer-events : none;
...
}
我刚刚在访问您的网站时通过 chrome inspector 添加了上述内容,它为我解决了问题。
关于javascript - CSS3 过渡在 div 或图像上效果不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164280/