简体   繁体   English

从整个 HTML 动态添加类到 img 标签

[英]Dynamically add class to img tag from entire HTML

I have an rich editor which adds text and images,to make the images responsive我有一个丰富的编辑器,可以添加文本和图像,使图像具有响应性

class="img-thumbnail"

is needed in all the image tags,so have used HtmlAgility pack to extract image tags from entire Html but how to add the class on each image tag.在所有图像标签中都需要,所以使用 HtmlAgility 包从整个 Html 中提取图像标签,但如何在每个图像标签上添加类。

Example例子

Input from html after extracting image tag提取图片标签后从html输入

<img src="http://domain.com/images/image1.jpg">

Expected预期的

<img src="http://domain.com/images/image1.jpg" class="img-thumbnail">

Code代码

 public string ParseImage(string pHtml)
    {

        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(pHtml);
        var imgs = doc.DocumentNode.SelectNodes("//img");

        foreach (var item in imgs)
        {
            string orig = item.Attributes["src"].Value;
            //Add class to each img tag.
        }
      }

I guess the problem lies in that you need to save the HTML before you display it.我想问题在于您需要在显示之前保存 HTML。 Otherwise HTML Agility Pack sometimes omits the changed attributes.否则 HTML Agility Pack 有时会忽略更改的属性。

public string ParseImage(string pHtml)
{

   HtmlDocument doc = new HtmlDocument();
   doc.LoadHtml(pHtml);
   var imgs = doc.DocumentNode.SelectNodes("//img");

    foreach (var item in imgs)
    {
        //string orig = item.Attributes["src"].Value;
        item.SetAttributeValue("class", "img-thumbnail");
        //Add class to each img tag.
    }
    using(StringWriter tw = new StringWriter ()){
        doc.Save(tw);
        return tw.ToString();
    }
 }

You can add attributes to all your image tags in css like this您可以像这样在 css 中为所有图像标签添加属性

.img-thumbnail
{
  // your class property
}

img {
.img-thumbnail
}

Here is a similar question.这是一个类似的问题。

I want to apply an existing CSS style to all labels on a page. 我想将现有的 CSS 样式应用于页面上的所有标签。 How? 如何?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM