【问题标题】:PHPDOM: how to edit style in HTML elementPHPDOM:如何在 HTML 元素中编辑样式
【发布时间】:2015-10-18 11:12:20
【问题描述】:

我最近发现了 PHPDom,发现它对处理 HTML 代码非常有用。不幸的是,在线文档有限,并且没有我所知道的全面的 PHPDom 手册。 (stockoverflow 中也没有 PHPdom 标签!!)

这是我遇到的问题。

我想改变一个html标签的样式,这是我正在使用的:

            $item = $dom->getElementById($name);
            $item->setAttribute('style', 'background-color:#FF0000;');
            $item = $dom->getElementById($name.'_error');
            $item->setAttribute('style', 'display:true;'); 

但是这段代码的结果是$name 和name.'_error' 中定义的样式被覆盖了。

为了解决这个问题,我正在寻找一种 PHPdom 方法,例如 editAttribute,它允许编辑属性而不覆盖该元素的现有样式属性。

有人知道如何解决这个问题吗?

【问题讨论】:

  • 最好检查一下这个问题。 stackoverflow.com/questions/16127142/…
  • 这无济于事,因为 .其实Linda需要把href整体替换掉,这不是我的情况。
  • 我找到了解决方案:$item->setAttribute('style', $item->getAttribute('style') . 'background-color:#FF0000;');@Sundar

标签: php html dom


【解决方案1】:

这意味着您需要解析和编辑属性中的 CSS 属性。

实际上,我在FluentDOM 中实现了这一点。您可以执行以下操作:

$fd = FluentDOM($html, 'text/html');
$fd
  ->find('//a')
  ->css['text-decoration'] = 'none';
echo (string)$fd;

此逻辑位于FluentDOM\Query\Css\Properties。您可以使用此对象来编辑样式属性字符串。

$style = new FluentDOM\Query\Css\Properties($node->getAttribute('style'));
$style['background-color'] = '#FF0000';
$node->setAttribute('style', $style); 

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2012-02-08
    • 2014-01-29
    • 2011-02-09
    相关资源
    最近更新 更多