I am creating a tutorial and want to fade every div on the page apart from the div I want the开发者_JAVA技巧m to see. How can I do this using fadeTo?
I currently have it set to fade the whole body. How can I set it to fade the body apart from div id "step2"?
Code:
<script type="text/javascript">
$("body").fadeTo("slow", 0.5, function() {
// Animation complete.
});
</script>
Hard to tell without seeing your HTML, but if step2
is a child of <body>
you could do this:
Try it out: http://jsfiddle.net/SS5Sm/
$("body").children(':not(#step2)').fadeTo("slow", 0.5, function() {
// Animation complete.
});
or
$("body > :not(#step2)").fadeTo("slow", 0.5, function() {
// Animation complete.
});
If it is more deeply nested, you could try this.
$("body > :not(:has(#step2))").fadeTo("slow", 0.5, function() {
// Animation complete.
});
Although it makes some additional assumptions about your HTML structure.
This sounds like a job for the not selector
A fade will always fade every element under and including the one you selected with jQuery. Unless the div you want to stay visible is directly under the body, this will be tricky. To achieve the effect you desire, you should clone the div you want visible, and absolutely position it in the same location as the original. That also means you'll need to put the main content that is getting hidden inside of a container div, so instead of fading the body, fade the container div, and put the cloned div at the top level directly under the body, after the container.
<body>
<div id="content-to-fade">
...<div id="div-i-want-">...</div>
</div>
<div id="copy-of-div-i-want">...</div>
</body>
so in the example, you would create "copy-of-div-i-want", append to the body and then call fadeTo on "content-to-fade".
This technique is a pretty common way of implementing drag and drop, because the copy can easily and efficiently be absolutely positioned around the screen.
You can just use css-selectors with JQuery :)
$("*:not(div#step2)").fadeTo(...)
It is basically impossible to do what you've described with the code you gave, because all elements have to be contained within the body tag, and since the opacity
property inherits, everything on the page will turn half transparent. Oh, and overriding the opacity
property on that single div
also won't work.
Instead, what you need to do is probably to move everything to another div
, and fade that one instead. Using the :not
selector may also work, but it isn't a catchall solution - be aware of your page structure.
精彩评论