网络科技

    今日:367| 主题:255979
收藏本版
互联网、科技极客的综合动态。

[其他] JavaScript for Web Designers: DOM Scripting

[复制链接]
此人是美好的 发表于 2016-10-19 04:52:35
268 6

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Before we do anything with a page, you and I need to have a talk about something very important: the Document Object Model. There are two purposes to the DOM: providing JavaScript with a map of all the elements on our page, and providing us with a set of methods for accessing those elements, their attributes, and their contents.
   Article Continues Below
  The “object” part of Document Object Model should make a lot more sense now than it did the first time the DOM came up, though: the DOM is a representation of a web page in the form of an object, made up of properties that represent each of the document’s child elements and subproperties representing each of those elements’ child elements, and so on. It’s objects all the way down.
   window : The Global Context

   Everything we do with JavaScript falls within the scope of a single object: window . The window object represents, predictably enough, the entire browser window. It contains the entire DOM, as well as—and this is the tricky part—the whole of JavaScript.
  When we first talked about variable scope, we touched on the concept of there being “global” and “local” scopes, meaning that a variable could be made available either to every part of our scripts or to their enclosing function alone.
   The window object is that global scope. All of the functions and methods built into JavaScript are built off of the window object. We don’t have to reference window constantly, of course, or you would’ve seen a lot of it before now—since window is the global scope, JavaScript checks window for any variables we haven’t defined ourselves. In fact, the console object that you’ve hopefully come to know and love is a method of the window object:
  [code]window.console.log
function log() { [native code] }[/code]   It’s hard to visualize globally vs. locally scoped variables before knowing about window , but much easier after: when we introduce a variable to the global scope, we’re making it a property of window —and since we don’t explicitly have to reference window whenever we’re accessing one of its properties or methods, we can call that variable anywhere in our scripts by just using its identifier. When we access an identifier, what we’re really doing is this:
  [code]function ourFunction() {
    var localVar = "I’m local.";
    globalVar = "I’m global.";

    return "I’m global too!";
};
undefined

window.ourFunction();
I’m global too!

window.localVar;
undefined

window.globalVar;
I’m global.[/code]   The DOM’s entire representation of the page is a property of window : specifically, window.document . Just entering window.document in your developer console will return all of the markup on the current page in one enormous string, which isn’t particularly useful—but everything on the page can be accessed as subproperties of window.document the exact same way. Remember that we don’t need to specify window in order to access its document property— window is the only game in town, after all.
  [code]document.head
...

document.body
...[/code]  Those two properties are themselves objects that contain properties that are objects, and so on down the chain. (“Everything is an object, kinda.”)
  Using the DOM

   The objects in window.document make up JavaScript’s map of the document, but it isn’t terribly useful for us—at least, not when we’re trying to access DOM nodes the way we’d access any other object. Winding our way through the document object manually would be a huge headache for us, and that means our scripts would completely fall apart as soon as any markup changed.
   But window.document isn’t just a representation of the page; it also provides us with a smarter API for accessing that information. For instance, if we want to find every p element on a page, we don’t have to write out a string of property keys—we use a helper method built into document that gathers them all into an array-like list for us. Open up any site you want—so long as it likely has a paragraph element or two in it—and try this out in your console:
  [code]document.getElementsByTagName( "p" );
[

...

,

...

,

...

,

...

][/code]  Since we’re dealing with such familiar data types, we already have some idea how to work with them:
  [code]var paragraphs = document.getElementsByTagName( "p" );
undefined

paragraphs.length
4

paragraphs[ 0 ];

...

[/code]   But DOM methods don’t give us arrays, strictly speaking. Methods like getElementsByTagName return “node lists,” which behave a lot like arrays. Each item in a nodeList refers to an individual node in the DOM—like a p or a div —and will come with a number of DOM-specific methods built in. For example, the innerHTML method will return any markup a node contains—elements, text, and so on—as a string:
  [code]var paragraphs = document.getElementsByTagName( "p" ),
    lastIndex = paragraphs.length – 1, /* Use the length of the `paragraphs` node list minus 1 (because of zero-indexing) to get the last paragraph on the page */
    lastParagraph = paragraphs[ lastIndex ];

lastParagraph.innerHTML;
And that’s how I spent my summer vacation.[/code]         
JavaScript for Web Designers: DOM Scripting-1 (represents,something,important,providing,contents)
         Fig 5.1: First drafts are always tough.       The same way these methods give us access to information on the rendered page, they allow us to alter that information, as well. For example, the innerHTML method does this the same way we’d change the value of any other object: a single equals sign, followed by the new value.
  [code]var paragraphs = document.getElementsByTagName( "p" ),
    firstParagraph = paragraphs[ 0 ];

firstParagraph.innerHTML = "Listen up, chumps:";
"Listen up, chumps:"[/code]   JavaScript’s map of the DOM works both ways: document is updated whenever any markup changes, and our markup is updated whenever anything within document changes (Fig 5.1).
  Likewise, the DOM API gives us a number of methods for creating, adding, and removing elements. They’re all more or less spelled out in plain English, so even though things can seem a little verbose, it isn’t too hard to break down.
  DOM Scripting

  Before we get started, let’s abandon our developer console for a bit. Ages ago now, we walked through setting up a bare-bones HTML template that pulls in a remote script, and we’re going to revisit that setup now. Between the knowledge you’ve gained about JavaScript so far and an introduction to the DOM, we’re done with just telling our console to parrot things back to us—it’s time to build something.
  We’re going to add a “cut” to an index page full of text—a teaser paragraph followed by a link to reveal the full text. We’re not going to make the user navigate to another page, though. Instead, we’ll use JavaScript to show the full text on the same page.
  Let’s start by setting up an HTML document that links out to an external stylesheet and external script file—nothing fancy. Both our stylesheet and script files are empty with .css and .js extensions, for now—I like to keep my CSS in a /css subdirectory and my JavaScript in a /js subdirectory, but do whatever makes you most comfortable.
  [code]

   
        
        
   
   

        
   
[/code]  We’re going to populate that page with several paragraphs of text. Any ol’ text you can find laying around will do, including—with apologies to the content strategists in the audience—a little old-fashioned lorem ipsum. We’re just mocking up a quick article page, like a blog post.
  [code]

   
        
        
   
   
        

JavaScript for Web Designers



        

In all fairness, I should start this book with an apology—not to you, reader, though I don’t doubt that I’ll owe you at least one by the time we get to the end. I owe JavaScript a number of apologies for the things I’ve said to it during the early years of my career, some of which were strong enough to etch glass.



        

This is my not-so-subtle way of saying that JavaScript can be a tricky thing to learn.



        [ … ]

        
   
[/code]  Feel free to open up the stylesheet and play with the typography, but don’t get too distracted. We’ll need to write a little CSS later, but for now: we’ve got scripting to do.
   We can break this script down into a few discrete tasks: we need to add a Read More link to the first paragraph, we need to hide all the p elements apart from the first one, and we need to reveal those hidden elements when the user interacts with the Read More link.
  We’ll start by adding that Read More link to the end of the first paragraph. Open up your still-empty script.js file and enter the following:
  [code]var newLink = document.createElement( "a" );[/code]   First, we’re intializing the variable newLink , which uses document.createElement( "a" ) to—just like it says on the tin—create a new a element. This element doesn’t really exist anywhere yet—to get it to appear on the page we’ll need to add it manually. First, though, without any attributes or contents isn’t very useful. Before adding it to the page, let’s populate it with whatever information it needs.
   We could do this after adding the link to the DOM, of course, but there’s no sense in making multiple updates to the element on the page instead of one update that adds the final result—doing all the work on that element before dropping it into the page helps keep our code predictable.
   Making a single trip to the DOM whenever possible is also better for performance—but performance micro-optimization is easy to obsess over. As you’ve seen, JavaScript frequently offers us multiple ways to do the same thing, and one of those methods may technically outperform the other. This invariably leads to “excessively clever” code—convoluted loops that require in-person explanations to make any sense at all, just for the sake of shaving off precious picoseconds of load time. I’ve done it; I still catch myself doing it; but you should try not to. So while making as few round-trips to the DOM as possible is a good habit to be in for the sake of performance, the main reason is that it keeps our code readable and predictable. By only making trips to the DOM when we really need to, we avoid repeating ourselves and we make our interaction points with the DOM more obvious for future maintainers of our scripts.
   So. Back to our empty, attribute-less floating in the JavaScript ether, totally independent of our document.
   Now we can use two other DOM interfaces to make that link more useful: setAttribute to give it attributes, and innerHTML to populate it with text. These have a slightly different syntax. We can just assign a string using innerHTML , the way we’d assign a value to any other object. setAttribute , on the other hand, expects two arguments: the attribute and the value we want for that attribute, in that order. Since we don’t actually plan to have this link go anywhere, we’ll just set a hash as the href —a link to the page you’re already on.
  [code]function ourFunction() {
    var localVar = "I’m local.";
    globalVar = "I’m global.";

    return "I’m global too!";
};
undefined

window.ourFunction();
I’m global too!

window.localVar;
undefined

window.globalVar;
I’m global.0[/code]   You’ll notice we’re using these interfaces on our stored reference to the element instead of on document itself. All the DOM’s nodes have access to methods like the ones we’re using here—we only use document.getElementsByTagName( "p" ) because we want to get all the paragraph elements in the document. If we only wanted to get all the paragraph elements inside a certain div , we could do the same thing with a reference to that div —something like ourSpecificDiv.getElementsByTagName( "p" ); . And since we’ll want to set the href attribute and the inner HTML of the link we’ve created, we reference these properties using newLink.setAttribute and newLink.innerHTML .
   Next: we want this link to come at the end of our first paragraph, so our script will need a way to reference that first paragraph. We already know that document.getElementsByTagName( "p" ) gives us a node list of all the paragraphs in the page. Since node lists behave like arrays, we can reference the first item in the node list one by using the index 0 .
  [code]function ourFunction() {
    var localVar = "I’m local.";
    globalVar = "I’m global.";

    return "I’m global too!";
};
undefined

window.ourFunction();
I’m global too!

window.localVar;
undefined

window.globalVar;
I’m global.1[/code]   For the sake of keeping our code readable, it’s a good idea to initialize our variables up at the top of a script—even if only by initializing them as undefined (by giving them an identifier but no value)—if we plan to assign them a value later on. This way we know all the identifiers in play.
   So now we have everything we need in order to append a link to the end of the first paragraph: the element that we want to append ( newLink ) and the element we want to append it to ( firstParagraph ).
   One of the built-in methods on all DOM nodes is appendChild , which—as the name implies—allows us to append a child element to that DOM node. We’ll call that appendChild method on our saved reference to the first paragraph in the document, passing it newLink as an argument.
  [code]function ourFunction() {
    var localVar = "I’m local.";
    globalVar = "I’m global.";

    return "I’m global too!";
};
undefined

window.ourFunction();
I’m global too!

window.localVar;
undefined

window.globalVar;
I’m global.2[/code]  Now—finally—we have something we can point at when we reload the page. If everything has gone according to plan, you’ll now have a Read More link at the end of the first paragraph on the page. If everything hasn’t gone according to plan—because of a misplaced semicolon or mismatched parentheses, for example—your developer console will give you a heads-up that something has gone wrong, so be sure to keep it open.
   Pretty close, but a little janky-looking—our link is crashing into the paragraph above it, since that link is display: inline by default (Fig 5.2).

JavaScript for Web Designers: DOM Scripting-2 (represents,something,important,providing,contents)
         Fig 5.2: Well, it’s a start.       We have a couple of options for dealing with this: I won’t get into all the various syntaxes here, but the DOM also gives us access to styling information about elements—though, in its most basic form, it will only allow us to read and change styling information associated with a style attribute. Just to get a feel for how that works, let’s change the link to display: inline-block and add a few pixels of margin to the left side, so it isn’t colliding with our text. Just like setting attributes, we’ll do this before we add the link to the page:
  [code]function ourFunction() {
    var localVar = "I’m local.";
    globalVar = "I’m global.";

    return "I’m global too!";
};
undefined

window.ourFunction();
I’m global too!

window.localVar;
undefined

window.globalVar;
I’m global.3[/code]   Well, adding those lines worked , but not without a couple of catches. First, let’s talk about that syntax (Fig 5.3).
123下一页
友荐云推荐




上一篇:Electric Objects发布数字画框EO2
下一篇:Mirai C&C Botnets
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

黄瑞琦 发表于 2016-10-19 05:47:21
只吃楼主,撸过过经验,小伙伴们都惊呆了
回复 支持 反对

使用道具 举报

shiler 发表于 2016-10-20 02:22:12
壁咚咚咚
回复 支持 反对

使用道具 举报

蓝蓝天上azf 发表于 2016-10-21 03:45:50
我死了,但是在烈火中我又站起来了,你猜是涅磐,还是尸变?
回复 支持 反对

使用道具 举报

Samuelcync 发表于 2016-10-25 23:39:42
香烟不乖,所以我们抽烟…
回复 支持 反对

使用道具 举报

wazyyan1 发表于 2016-10-26 12:18:17
我女友不当尼姑的原因是她四级没过,庵里不收.
回复 支持 反对

使用道具 举报

aef25u 发表于 2016-11-6 05:25:04
刚起床,睁开眼就看到楼主的帖子了,顶一下!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2017 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表