Locally defined styles and animation in JavaScript
I am learning about JavaScript, and in the te开发者_JS百科xt it says you must us locally defined styles for animation. i.e. A HTML style tag. Does this make sense, and if so, why is this necessary? Thanks in advance.
No, this is not necessary.
You can do it in two basic ways.
Dynamically change the style:
<p id="myElement">Here is some text to animate</p>
<script>
var pixels = 10; // e.g., if this were a dynamically changing variable
document.getElementById('myElement').style.width = pixels+'px';
</script>
Dynamically change the class:
<style>
.tiny {width:10px}
</style>
<p id="myElement">Here is some text to animate</p>
<script>
document.getElementById('myElement').className = 'tiny';
</script>
The latter approach is probably a better practice because it gives control to the designer to control everything from CSS, while letting the JavaScript programmer focus on functionality only.
However, in the case of transitions, where you wish to change values dynamically (e.g., incrementing the width by 1 every second), it is not practical to define a class for each possible width along the way. However, it is possible for you to query the stylesheet itself to get this info. CSS Variables will make this easier if they are implemented, but currently you can use something like the function getCSSPropertyValue at https://gist.github.com/990313 to get the begin and end values from classes defined in the stylesheet, while handling the style transitions with the style property.
var beginWidth = parseInt(getCSSPropertyValue('.small', 'width'));
var endWidth = parseInt(getCSSPropertyValue('.large', 'width'));
var itvl = setInterval(function () {
if (beginWidth++ > endWidth) {
clearInterval(itvl);
}
document.getElementById('myElement').style.width = beginWidth + 'px';
}, 10);
They may be referring to changing the style locally in javascript. In order to do that you utilize the style attribute of each element.
element.style.width = "100px";
would change the style to a width of 100px. This is how you change the appearance of elements with javascript.
Perhaps what the text means is that when you do something like call the jQuery animate()
function, for instance, passing in CSS properties, those properties are set via the style
attribute of the HTML element. This makes sense because you'll want these rules to override any pre-defined rules from your stylesheets.
Example: http://jsfiddle.net/jRKJx/
If you inspect the <div>
after the animation runs, you'll see that jQuery set the style
attribute on the element.
精彩评论