为了账号安全,请及时绑定邮箱和手机立即绑定

获取段落对齐值

获取段落对齐值

冉冉说 2021-10-07 10:42:59
我想获得段落对齐的值以放入 IF 条件。下面的示例失败并且无法运行这是代码const paragraph = document.getElementsByTagName('p');for (let i = 0; i < paragraph.length; i++) {    if (paragraph[i].getAttribute('align').value == 'center') {        console.log('paragraph' + i + 'centered')    }}<p align="center">this is a paragraph!</p>正如您所指出的,属性中不存在 value 属性。如何获得align的值,无论是“center, left, right ..”?
查看完整描述

1 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

const paragraph = document.getElementsByTagName('p');

for (let i = 0; i < paragraph.length; i++) {

    if (paragraph[i].getAttribute('align') == 'center') {

        console.log('paragraph' + i + 'centered')

    }

}

<p align="center">this is a paragraph!</p>

但该align属性已过时且已弃用。text-align即使阅读样式需要更多代码,也最好使用。


const paragraph = document.getElementsByTagName('p');


for (let i = 0; i < paragraph.length; i++) {

  let computed = window.getComputedStyle(paragraph[i], null);

  let alignment = computed.getPropertyValue('text-align')

  if (alignment == 'center') {

    console.log('paragraph' + i + 'centered')

  }

}

p {

  text-align: center;

}

<p>this is a paragraph!</p>


查看完整回答
反对 回复 2021-10-07
  • 1 回答
  • 0 关注
  • 256 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信