Fully illustrated Scrollleft,scrollwidth,clientwidth,offsetwidth

Source: Internet
Author: User

Sometimes the project will use JS to get the element position to locate elements, I opened a lot of graphics online, code, eventually I get dizzy, or combined with the online self to summarize, first look at the online:

the DOM is defined as

scrollleft: Sets or gets the distance between the left edge of the object and the leftmost of the currently visible content in the window
scrolltop: Sets or gets the distance between the top of the object and the top of the visible content in the window
scrollwidth: Gets the scrolling width of the object
offsetheight: Gets the height of the object relative to the layout or parent coordinates specified by the parent coordinate OffsetParent property
offsetleft: Gets the calculated left position of the object relative to the layout or the parent coordinate specified by the OffsetParent property
OffsetTop: Gets the computed top position of the object relative to the layout or the parent coordinate specified by the OffsetTop property
event.clientx Horizontal coordinates of relative documents
event.clienty Vertical coordinates of relative documents
event.offsetx Horizontal coordinates relative to the container
event.offsety The vertical coordinate of the relative container
Document.documentElement.scrollTop The vertical scrolling value

Gets the location property of an element that can be

    • Htmlelement.offsetleft
    • Htmlelement.offsettop

However, the values stored by these two properties are not the absolute position of the element relative to the entire browser canvas, but rather the relative position of the position of the parent element, which means that the values are computed as a (0,0) point in the upper-left corner of their parent element .  So we're going to get her absolute position, then we have to get the position of his parent element in turn, then get the Offersetleft and offersettop of the parent element of its parent element, always recursively to the browser's entire canvas at a distance, for example ( Be sure to pay attention to the path relative to the parent tag! )


/* Gets the element's ordinate */function GetTop (e) {   var offset=e.offsettop;   if (e.offsetparent!=null) {     offset+=gettop (e.offsetparent);   }            return offset;} /* Gets the element's horizontal axis */function GetLeft (e) {   var offset=e.offsetleft;   if (e.offsetparent!=null) {      offset+=getleft (e.offsetparent);   }    return offset;}
gets the absolute position of the element, which is nothing more than the element from the left side of the browser (top), we can change a little bit to get a method


function Getelempos (obj) {        var pos = {"Top": 0, "left": 0};         if (obj.offsetparent) {           while (obj.offsetparent) {             pos.top + = obj.offsettop;             Pos.left + = Obj.offsetleft;             obj = obj.offsetparent;           }         } else if (obj.x) {           Pos.left + = obj.x;         } else if (obj.x) {           pos.top + = obj.y;         }         return {x:pos.left, y:pos.top};}
event.clientx+document.documentelement.scrolltop Horizontal coordinates of relative documents + amount of vertical scrolling
the above mainly refers to IE, Firefox differences are as follows:
IE6.0, ff1.06+:
clientwidth = width + padding
clientheight = height + padding
offsetwidth = width + padding + border
offsetheight = height + padding + border
ie5.0/5.5:
clientwidth = Width-border
clientheight = Height-border
offsetwidth = width
offsetheight = height (need to mention: Margin attribute in CSS, regardless of clientwidth, offsetwidth, ClientHeight, offsetheight)

  

The red part above is very clear offsetwidth, now look

in other words, scrollleft: Sets or gets the distance between the left edge of the object and the leftmost of the currently visible content in the window.

before saying, first look at a paragraph of text:

scrollleft: Sets or gets the distance between the left edge of the object and the leftmost of the currently visible content in the window.

 

1, InnerHTML:inner (inside, Element), InnerHTML is used to change the object DH internal HTML statement. And the a.innerhtml=b.innerhtml of this effect is that B assigns its own HTML element to a, which is used here as a clone.

2, offsetwidth: refers to the width of the object including the border. Unlike ClientWidth, clientwidth refers to objects that do not include borders that include only the actual width of the content.

       3, scrollleft: We know that scroll is a rolling axis, so scrollleft is the distance from the left-hand side when the scroll axis rolls out from left to right. The Scroll has four directions, and we'll do it in turn.

       Understanding of these three basic attributes, we have the idea of a preliminary implementation of scrolling. First of all we need to know that a block is so wide, if the contents of the inside and the outside wrapped their parent tag width, then the width of the scroll bar must be as wide as the content, there is no roll. The content is hidden only if it is larger than the parent tag content and the fixed width is set to the parent label. This allows you to manually drag the scroll bar even when we do not have control over JS. To understand this after the cycle of scrolling, since the child label to go beyond the parent tag to achieve scrolling, then the cycle of scrolling, the loop to show a group of pictures do not need two sets of identical pictures end-to-end, when the first piece of the tail roll after the second block of the header immediately, of course, control the accuracy to 1px, Users are simply unaware that two sets of pictures are doing scrolling because they are the same. After saying the principle, and then the realization method, We already know what scrollleft means, so to roll the picture to the left is undoubtedly increasing its value, When we manually drag the scroll bar will also observe the right to drag the picture is to do moving, scrollleft distance is increasing. In other words, to achieve the child label picture Scrolling, you have to control . Plus the timer, let How often does automatic picture scrolling last? look at the code below, in the structure of the HTML also need to do a detailed explanation.

This is an online find, to be clear scrollleft is the parent tag,scrollleft is a value, the parent tag refers to the element that produces the scrollbar, and the scroll bar also belongs to the parent tag 。


let's look at a simple example:


html:<div id= "Div1" ><div id= "Div2" ><!- -the div here mainly controls the function of not wrapping, because it also wraps two div--><div id= "div3" ><a href= "#" > </a><a href= "#" ></a><a href= "#" ></a><a href=" # "></a><a href=" # "></a></div><div id= "Div4" >&nbsp;</div></div></div> 
using table authoring can also reduce the CSS styling, eliminating a lot of floats. However, the spacing between the TD elements in the table needs to be resolved, as the above code has been written to add cellspacing= "0" cellpadding= "0" to the table tag of the package image, which can also be written directly in CSS, table{ Border-collapse:collapse, the spacing between TD can be removed, the spacing caused by the picture folding is solved by floating, and the habit we have to develop is to set the Overflow:hidden of the parent tag when the child element floats, otherwise its parent tag will No longer wrap the sub-label, add border after you can see.


css:body {margin:0;} #div {border:5px #0ff solid;height:160px;width:800px;overflow:hidden;overflow-x:scroll;} #div table td {Overflow:hidden} #div img {float:left;}



Js:<script type= "Text/javascript" >vardiv=document.getelementbyid ("div");//Outermost Divvar td1= document.getElementById ("TD1");//First TD, Inside package picture var Td2=document.getelementbyid ("Td2");// tdtd2.innerhtml=td1.innerhtml;//without package content (image) assigns the contents of the first TD to the second Tdfunction HS1 () {div.scrollleft++;// Peripheral parent Tag Div ScrollLeft Gaga (explained above)}var Id=setinterval (hs1,10);//10 milliseconds plus 1 for initial scrolling </script>



with the beginning of the initial scrolling of the picture, we can see that when the rolling axis rolls to the right end, it doesn't scroll anymore, how do we keep it rolling from the beginning? Please look at the following code: (Follow the above code to do the extension )

<script type= "Text/javascript" >vardiv=document.getelementbyid ("div"); Vartd1=document.getelementbyid ("TD1") ); Vartd2=document.getelementbyid ("Td2"); Td2.innerhtml=td1.innerhtml;functionhs1 () {if (td1.offsetwidth<= Div.scrollleft) {//Scroll axis stopped, the picture must also roll to the end, then judge the first or second (both width)//width (or plus or without edge) is not already greater than or equal to the parent tag Div scrollleftdiv.scrollleft=0 If the above conditions are set up, then the scrollleft of Div will continue ++}}var id=setinterval (hs1,10) from scratch}else{div.scrollleft++;//not in the above situation; </script >



running here has already achieved seamless scrolling, then the next thing to consider is when the user mouse on the stop scrolling, left to continue scrolling. Thought is also easy to understand, is to put on the time to clear the timer, leaving the time plus a timer. In fact, do not listen to the event to do this step only two words, very easy. But in order to prevent event bubbling, we still need to use the method of time monitoring to solve.

event bubbling: In CSS, a child tag inherits the style of the parent tag. JS, because many browsers are not layered, can not be layered parsing, child tags will inherit the parent tag action caused event bubbling. So we try to stop bubbling.

The above code extends:

<script type= "Text/javascript" >vardiv=document.getelementbyid ("div"); Vartd1=document.getelementbyid ("TD1") ); Vartd2=document.getelementbyid ("Td2"); Td2.innerhtml=td1.innerhtml;functionhs1 () {if (td1.offsetwidth<= Div.scrollleft) {div.scrollleft=0;} else{div.scrollleft++;}} Varid=setinterval (hs1,10); Functionhs2 () {addEventHandler (div, "mouseover", function () {clearinterval (id);}); /Using the event listener method, if this method is only called once, it can be written directly in the function section here addEventHandler (Div, "mouseout", function () {id=setinterval (hs1,10);});} HS2 (); function addEventHandler (Target,type,func) {if (Target.addeventlistener) {Target.addeventlistener (Type,func, FALSE);} else if (target.attachevent) {target.attachevent ("on" +type,func);} else{target["on" +type]=func;}} Event snooping (an understanding of event snooping is noted in "Four Ways to Tab through") </script>



Step by step to achieve a seamless cycle of scrolling and listen to the user action stop continue, it is necessary to continue to consider another effect, when the picture scroll to a certain position will automatically stop, how long after the stop to continue to perform normal scrolling, the user will stop when the mouse on the left, continue. The effect we all can think of is the first command Div ScrollLeft to where to clear out the timer, in the use of SetTimeout Timer control how long it continues to scroll. So how can we get to how long it takes to stop it, and notice that "every" I've tried to add, obviously it won't work, and the round of infinite loops should be added to the time. But our classmates thought of a very ingenious way, to seek the remainder. The calculation of the remainder of the symbol is%, to seek more than a multiplier, you can realize how far each forward to clear out the timer method. For code parsing, see the code below:

<script type= "Text/javascript" >vardiv=document.getelementbyid ("div"); Vartd1=document.getelementbyid ("TD1") ); Vartd2=document.getelementbyid ("Td2"); td2.innerhtml=td1.innerhtml;varidd=null;//here declares the timer IDD, Otherwise the object is not read and there is no object to execute on its command times wrong. function HS1 () {if (td1.offsetwidth<=div.scrollleft) {div.scrollleft=0;} else{div.scrollleft++;} if (div.scrollleft%160==0) {//Here is the judgment of the remainder, whenever the scrollleft of the div can divide the position of the value 160, (value we can set ourselves), Clearinterval (ID);//the timer is cleared. Idd=settimeout ("Id=setinterval (hs1,10)", "N"),//settimeout timer, the control stops for one second and resumes execution of the timer ID, which is to continue scrolling}}var id=setinterval ( hs1,10); function HS2 () {addEventHandler (div, "mouseover", function () {if (IDD) {cleartimeout (IDD);} Clearinterval (ID);}); /When the user mouse is placed, it will be more than one sentence, if you are running the IDD timer is also cleared. addEventHandler (Div, "mouseout", function () {id=setinterval (hs1,10);}); HS2 (); function addEventHandler (Target,type,func) {if (Target.addeventlistener) {Target.addeventlistener (Type,func, FALSE);} else if (target.attachevent) {target.attachevent ("on" +type,func);} else{target["on" +type]=func;}} Event Monitoring </script> 






Fully illustrated Scrollleft,scrollwidth,clientwidth,offsetwidth

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.