获取元素的内容宽度 [英] Get content width of an element

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

问题描述

offsetWidth 现在还不够好,因为这包括填充和边框宽度。我想找出元素的内容宽度。是否有属性,或者我必须采用offsetWidth然后从计算样式中减去填充和边框宽度?

offsetWidth isn't good enough for me right now, as this includes padding and border width. I want to find out the content width of the element. Is there a property for that, or do I have to take the offsetWidth and then subtract the padding and border width from the computed style?

推荐答案

由于谷歌搜索时首先出现,但还没有合适的答案,这里有一个:

Since this comes up first when googling but doesn't have an appropriate answer yet, here's one:

function getContentWidth (element) {
  var styles = getComputedStyle(element)

  return element.clientWidth
    - parseFloat(styles.paddingLeft)
    - parseFloat(styles.paddingRight)
}

基本上,我们首先得到元素的宽度,包括填充( clientWidth )然后左右填充填充。我们需要 parseFloat 填充,因为它们来自 px -suffixed strings。

Basically, we first get the element's width including the padding (clientWidth) and then substract the padding left and right. We need to parseFloat the paddings because they come as px-suffixed strings.

我在 CodePen ,请查看!

这篇关于获取元素的内容宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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