Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

javascript - How do i calculate the height of toolbars, address bars and other navigation tools in pixels?

Basically i need to know how many pixels the y axis is from the top left of the screen until i reach the actual web window. Does anyone have any ideas...?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know how you can return the height of external component, but I took this from http://www.alexandre-gomes.com/?p=115 and adapted it to also return scroll bar height.

Tested working in the following browsers :

  • Chrome
  • FF 9+
  • IE9 (thank you Pax0r)
  • Opera (thank you Pax0r)

If anyone can test it in other browsers and give me feedback, I will modify this answer accordingly.

Using JQuery :

jQuery.getScrollBarSize = function() {
   var inner = $('<p></p>').css({
      'width':'100%',
      'height':'100%'
   });
   var outer = $('<div></div>').css({
      'position':'absolute',
      'width':'100px',
      'height':'100px',
      'top':'0',
      'left':'0',
      'visibility':'hidden',
      'overflow':'hidden'
   }).append(inner);

   $(document.body).append(outer);

   var w1 = inner.width(), h1 = inner.height();
   outer.css('overflow','scroll');
   var w2 = inner.width(), h2 = inner.height();
   if (w1 == w2 && outer[0].clientWidth) {
      w2 = outer[0].clientWidth;
   }
   if (h1 == h2 && outer[0].clientHeight) {
      h2 = outer[0].clientHeight;
   }

   outer.detach();

   return [(w1 - w2),(h1 - h2)];
};

alert( $.getScrollBarSize() ); // in Chrome = [15,15] in FF = [16,16]

Without JQuery

function getScrollBarSize () {  
   var inner = document.createElement('p');  
   inner.style.width = "100%";  
   inner.style.height = "100%";  

   var outer = document.createElement('div');  
   outer.style.position = "absolute";  
   outer.style.top = "0px";  
   outer.style.left = "0px";  
   outer.style.visibility = "hidden";  
   outer.style.width = "100px";  
   outer.style.height = "100px";  
   outer.style.overflow = "hidden";  
   outer.appendChild (inner);  

   document.body.appendChild (outer);  

   var w1 = inner.offsetWidth;  
   var h1 = inner.offsetHeight;
   outer.style.overflow = 'scroll';  
   var w2 = inner.offsetWidth;  
   var h2 = inner.offsetHeight;
   if (w1 == w2) w2 = outer.clientWidth;
   if (h1 == h2) h2 = outer.clientHeight;   

   document.body.removeChild (outer);  

   return [(w1 - w2),(h1 - h2)];  
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...