JavaScript image toggling click
I working on image toggling, first click should hide the image and second click should display the image again. I got some thing working, but the issue is, on first click it is doing nothing and on second click toggling gets started. Hope there is some thing wrong in my code. Please advise.
<img src="img/1.jpg" width="449" height="600" class="one" id="one" style="opacity=1">
<img src="img/2.jpg" width="450" height="600" class="two">
function toggle(obj) {
var el = document.getElementById("one");
if ( el.style.opacity != 0 ) {
el.style.opacity = 0;
}
else {
开发者_StackOverflow社区 el.style.opacity = 1;
}
}
one.addEventListener("click", toggle, false);
style="opacity=1"
should be style="opacity:1"
. The rule, as you've written it, is invalid and will be ignored, so the first click on the element will set the opacity to 1 (which is the default anyway).
nb, you could refactor your function to look like this:
function toggle(obj) {
var el = document.getElementById("one");
el.style.opacity = +!+el.style.opacity;
// or, using bitwise XOR assignment to keep @Raynos happy
// el.style.opacity ^= 1;
}
Working demo: http://jsfiddle.net/AndyE/se29y/
This converts the current value from a string, e.g. "1"
to a number, e.g. 1
, then negates the "truthiness" of that number, !1 === false
, then converts the resulting boolean back to a number again before it is assigned to opacity
. This means each click toggles the value to its opposite.
Of course, as @casablanca's answer points out, visibility
is more appropriate (and more widely supported) for in-place hiding of elements, but a hidden element cannot be clicked to be shown again (thanks @Shadow Wizard).
Don't use opacity
to show/hide elements -- use visibility
instead with the values visible
or hidden
.
function toggle(obj) {
var el = document.getElementById("one");
el.style.opacity = el.style.opacity^1;
}
Because converting to integer twice in a single expression is stupid.
Unfortunately and unsurprisingly, each browser has its own implementation of opacity.. so here is cross browser (IE, Chrome, Firefox) version of the original code:
function Toggle(element) {
var curOpacity;
if (typeof element.style.filter != "undefined") {
curOpacity = parseInt(element.style.filter.split("=")[1]);
if (isNaN(curOpacity))
curOpacity = 100;
element.style.filter = "alpha (opacity=" + (100 - curOpacity) + ")";
}
else {
curOpacity = element.style.opacity || 1;
element.style.opacity = +!+curOpacity;
}
}
To apply this on all images at page load:
window.onload = function() {
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++)
images[i].onclick = function() { Toggle(this); };
}
Working test case with cute cats: http://jsfiddle.net/2sXVQ/2/ :)
精彩评论