div滚动条宽度 [英] div scrollbar width

查看:126
本文介绍了div滚动条宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用javascript / jquery有一种简单的方法来获取滚动条的宽度吗?
我需要获得溢出的div的宽度+滚动条的宽度。

Is there an easy way to get the width of a scrollbar using javascript / jquery ? I need to get the width of a div that overflows + whatever width the scroll bar is.

谢谢

推荐答案

如果你正在使用jquery,试试这个:

if you're using jquery, try this:

function getScrollbarWidth() 
{
    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div></div>'); 
    $('body').append(div); 
    var w1 = $('div', div).innerWidth(); 
    div.css('overflow-y', 'auto'); 
    var w2 = $('div', div).innerWidth(); 
    $(div).remove(); 
    return (w1 - w2);
}

我在我正在进行的项目中使用它并且它有效喜欢魅力。它通过以下方式得到滚动条宽度:

i'm using this in the project i'm working on and it works like a charm. it gets the scrollbar-width by:


  1. 将包含溢出内容的div附加到正文(在不可见区域,-200px到顶部/左侧)

  2. 设置溢出为隐藏

  3. 获取宽度

  4. 设置溢出到 auto (获取滚动条)

  5. 获取宽度

  6. 减去两个宽度以获得滚动条的宽度

  1. appending a div with overflowing content to the body (in a non-visible area, -200px to top/left)
  2. set overflow to hidden
  3. get the width
  4. set overflow to auto (to get scrollbars)
  5. get the width
  6. substract both widths to get width of the scrollbar

所以你需要做的是获得你的宽度div( $('#mydiv')。width())并添加滚动条宽度:

so what you'll have to do is getting the width of your div ($('#mydiv').width()) and add the scrollbar-width:

var completewidth = $('#mydiv').width() + getScrollbarWidth();

这篇关于div滚动条宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆