检查 Javascript 中是否存在滚动条?
我正在构建一个小便笺应用程序来娱乐,有时会发生这种情况:
(这是因为第一个单词比注释的宽度。)
有没有办法用 Javascript 检查滚动条是否存在?如果我能做到这一点,我可以调整注释的大小,直到它包含没有滚动条的文本。
I'm building a little sticky notes app for fun, and sometimes this happens:
(It's because the first word is wider than the width of the note.)
Is there a way to check whether the scrollbar is present with Javascript? If I can do that, I can resize the note until it contains the text without the scrollbar.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果此 CSS3 属性对于其容器来说太大,则会破坏其中的单词:
word-wrap: normal;
切换样式这基本上适用于每个浏览器,无论您相信与否,对该属性的支持最早可以追溯到 IE5。这要归功于 Louis Lazaris 的文章,自动换行:适用于的 CSS3 属性每个浏览器。
This CSS3 property will break a word within if it is too large for its container:
word-wrap: normal;
to toggle styleThis works in basically every browser and believe it or not, support for the property goes as far back as IE5. Credit for this goes to Louis Lazaris for his post, Word-Wrap: A CSS3 Property That Works in Every Browser.
这是一种完成OP要求的方法,如果它有滚动条,则加宽div,直到不再有滚动条:
参见示例→
Here's a way to accomplish what the OP asked for, to widen a div if it has a scroll bar until there's no longer one:
See example →
为了获得最佳的跨浏览器支持,我建议使用自动换行方法,并为元素指定一个设定的宽度(100% 或某个像素宽度),这样它就不会变宽。这应该提供最好的解决方案。
还可以设置overflow-x:hidden;简单地隐藏滚动条,但它在 IE7/8 中不起作用,并且还会导致溢出的文本不显示而不是换行,这可能不是您想要的。
For best cross-browser support I would recommend the word-wrap approach plus giving the element a set width (100%, or some pixel width) so it does not widen. This should provide the best solution.
You can also set overflow-x: hidden; to simply hide the scroll bar but it does not work in IE7/8 and also will cause the overflowed text to be not displayed instead of wrapped, which is probably not what you want.
我在类似情况下所做的是将文本附加到隐藏可见性的临时元素中,测量它,如果太大,则采取一些措施来解决它(这可能包括手动包装插入 BR 的文本,或者只是扩大最终元素您最终将文本放入其中)。这比使用 word-wrap:break-word; 提供了更多的控制权。
What I've done in similar circumstances is append the text to a temporary element with visibility hidden, measure it, and if too large, do something to address it (which could include manually wrapping the text inserting BRs, or just widening the final element that you eventually place the text into). This gives a lot more control than using word-wrap: break-word;