Changing An Image While Click Is Held
I am looking to change an image of a button from when a click is held, then change back upon click release. I currently have a flat image, and I want it to change to one with an in
Solution 1:
Simple solution
.image-swap {
cursor: pointer;
}
.image-swap>img, .image-swap:active>img:first-child {
display: none;
}
.image-swap>img:first-child, .image-swap:active>img:last-child {
display: block;
}
<divclass="image-swap"><imgsrc="http://blog.hvidtfeldts.net/media/city7.png" /><imgsrc="http://blog.hvidtfeldts.net/media/city2.png" /></div>
Remove select and drag effect
.image-swap {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
cursor: pointer;
}
.image-swap>img {
pointer-events: none;
display: none;
}
.image-swap>img:first-child {
display: block;
}
.image-swap:active>img:first-child {
display: none;
}
.image-swap:active>img:last-child {
display: block;
}
<divclass="image-swap"><imgsrc="http://blog.hvidtfeldts.net/media/city7.png" /><imgsrc="http://blog.hvidtfeldts.net/media/city2.png" /></div>
Smooth transition
.image-swap {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
cursor: pointer;
position: relative;
}
.image-swap>img {
pointer-events: none;
transition: all 0.6s;
position: absolute;
opacity: 0;
left: 0;
}
.image-swap>img:first-child {
position: static;
opacity: 1;
}
.image-swap:active>img:first-child {
opacity: 0;
}
.image-swap:active>img:last-child {
opacity: 1;
}
<divclass="image-swap"><imgsrc="http://blog.hvidtfeldts.net/media/city7.png" /><imgsrc="http://blog.hvidtfeldts.net/media/city2.png" /></div>
If you want you could give classes to the images like base-img
and active-img
So you could replace the :first-child
with .base-img
and :last-child
with .active-img
Solution 2:
Have a look at this very simple Proof Of Concept solution (based on your question and the comments):
functionmousedown() {
var el = document.getElementById("image01");
el.setAttribute("src", "http://blog.fantasy.co/wp-content/uploads/2013/02/feature_Net.jpg")
}
functionresetImage() {
var el = document.getElementById("image01");
el.setAttribute("src", "https://camo.githubusercontent.com/b87a252140848659b80b0d2297e32dc62afee0cf/68747470733a2f2f646f63732e6d6963726f736f66742e636f6d2f656e2d75732f646f746e65742f61727469636c65732f696d616765732f6875622f6e6574636f72652e737667")
}
<imgid="image01"src="https://camo.githubusercontent.com/b87a252140848659b80b0d2297e32dc62afee0cf/68747470733a2f2f646f63732e6d6963726f736f66742e636f6d2f656e2d75732f646f746e65742f61727469636c65732f696d616765732f6875622f6e6574636f72652e737667"alt="image"onmousedown="mousedown()"onmouseup="resetImage();"onmouseleave="resetImage();" />
Normally I would advise to use CSS (and maybe stitched images if you still need more than one) to accomplish this effect.
Post a Comment for "Changing An Image While Click Is Held"