繁体   English   中英

鼠标移动时如何使图像变色?

[英]How to make image change color while mouse is moving over?

首先,对这个怪异的标题感到抱歉,我真的不知道一种更好的描述方式。

基本上,我希望图像在鼠标移动(悬停)于其上方时改变颜色,但要使其在鼠标静止时停止,

鼠标静止不动时,颜色不会改变,

鼠标移动时,颜色会改变。

我知道CSS中有hover属性,但是它只有2种状态,当鼠标悬停在其上时,当鼠标不在其上时,我正在寻找的东西有些棘手。

希望能解释一下:/

请尝试以下方法:

document.getElementById("myDiv").onmousemove = function() {
  //Set random background color
  myDiv.style.backgroundColor = "#" + ((1 << 24) * Math.random() | 0).toString(16);
}

演示:

 document.getElementById("myDiv").onmousemove = function() { //Set random background color myDiv.style.backgroundColor = "#" + ((1 << 24) * Math.random() | 0).toString(16); } 
 #myDiv { width: 150px; height: 150px; background-color: #ccc; text-align: center; line-height: 140px; } 
 <div id="myDiv">Hover ME !</div> 

您可以使用CSS动画来实现此目的,可以使用Javascript在鼠标移到图像上或停止在图像上移动时切换类。

图像将需要包装在另一个标签中(如果尚未包装),然后需要向该标签添加一个伪元素,该元素应直接位于图像顶部,初始opacity0 通过设置伪元素的mix-blend-mode属性,我们确保图像在伪元素后面可见。 当鼠标第一次在图像上移动时,可以选择将其转换为灰度,然后伪元素的background-color开始动画显示。 当鼠标停止移动时,JavaScript中的超时会将一个类添加到父元素,该类将伪元素的animation-play-state属性设置为paused并且当再次移动鼠标时,将删除该类。

您可以通过编辑CSS来优化和调整其中的所有内容(例如,删除图像的filter ,添加/删除keyframes ,更改mix-blend-mode ,调整animation-duration ),而无需触摸JavaScript。

 var figure=document.querySelector("figure"), img=figure.querySelector("img"), timer; img.addEventListener("mousemove",function(){ clearTimeout(timer); figure.classList.remove("paused"); setTimeout(function(){ figure.classList.add("paused"); },300); },0); 
 *{box-sizing:border-box;margin:0;padding:0;} figure{ display:inline-block; position:relative; } img{ vertical-align:middle; transition:-webkit-filter .25s linear 99999s,filter .25s linear 99999s; } img:hover{ -webkit-filter:grayscale(1); filter:grayscale(1); transition-delay:0s; } figure::after{ animation:colours 5s linear infinite; bottom:0; content:""; left:0; mix-blend-mode:overlay; opacity:0; pointer-events:none; position:absolute; right:0; top:0; transition:opacity .25s linear 99999s; } figure:hover::after{ opacity:.75; transition-delay:0s; } figure.paused::after{ animation-play-state:paused; } @keyframes colours{ 0%{background:#f00;} 16.667%{background:#ff0;} 33.333%{background:#0f0;} 50%{background:#0ff;} 66.667%{background:#00f;} 83.333%{background:#f0f;} 100%{background:#f00;} } 
 <figure> <img src="https://unsplash.it/500/500/?random"> </figure> 

我在这里发布,因为我几乎需要像这样的东西。 我需要在每次鼠标移动时更改背景位置。 图像被设置为背景,这是图像:

http://pbdlbd.org/ipositive/wp-content/uploads/2015/02/one10.jpg

我想在每次鼠标移动时移动背景位置。 此图像有4个部分(每个部分的高度为523px),首先将显示顶部,将鼠标移到上面将显示第二部分,在另一个鼠标上将显示第三部分,在第四部分之后将重复显示鼠标移到它上面。 从图像中删除鼠标后,它将显示图像的默认顶部。

像这样:

document.getElementById("#ipos .flex_cell").onmousemove = function() {
  //Set background position 523px bottom on each mouse move
  #ipos .flex_cell.style.background-position = center -523px (here i can't make it so that it changes to -1046px by code);
}

是网站

TIA

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM