开发者

JavaScript add methods to all "visible" elements

I've made my fade in code. It's ok, it's working. I know that there are better alternatives (like JQuery) but I want to learn. I've read JQuery's code but i don't get it. I want to add my fade in code (as a method) to every visible element (div's, span, p, etc...). So, I want to be able to call fadeIn by this way:

var div = document.getElementById('div');
...
div.fadeIn(500);
span.fadeIn(50);

How could I do that? Thank you.

UPDATE: My new code is working in Firefox and Google Chrome. Thank you very much!

<html>
    <head>
        <title>Fade In</title>
        <style type="text/css">
        div#d {
            color: #fff;
            background: #000;
            margin: 0 auto;
            text-align: center;
            padding: 5px;
            width: 500px;
        }
        </style>
    </head>
    <body>
        <div id="d">
            <p>Div</p>
        </div>
        <script type="text/javascript">
        HTMLElement.prototype.fa开发者_如何学CdeIn = function(milliseconds) {
            var intervalID = null,
                self = this;

            if(!this.style.opacity) {
                this.style.opacity = 0;
            }

            intervalID = window.setInterval(function() {
                /* Replace call == Google Chrome fix */
                var opacity = parseFloat(self.style.opacity.replace(',', '.'), 10);

                if(opacity < 1) {
                    opacity += 0.1;
                    self.style.opacity = opacity.toString();
                }
                else {
                    window.clearInterval(intervalID);
                }
            }, milliseconds);
        }

        document.getElementById('d').fadeIn(100);
        </script>
    </body>
</html>


You would have to extend the HTMLElement.prototype to have these methods, however it is inconsistently supported throughout all browsers, which is the reason why jQuery was created to begin with - to provide a consistent abstracted interface wrapper which gives magical methods like fadeIn to DOM elements.

So you can

  • Try to extend HTMLElement.prototype for browsers that support it and ignore IE and the like, and try to achieve consistency in modern browsers
  • Try and fail at consistently supporting the extending of HTMLElement.prototype for all browsers
  • Attempt to mimic an interface such as jQuery's
  • use jQuery

If it's strictly for learning purposes then go ahead and attempt. If it's for production use, I would recommend the latter ( using jQuery ), or not attempting to use that prototypal invocation syntax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜