«

处理后端返回的html代码中样式代码

六思逸 发布于 阅读:3130 JavaScript


                        // 处理返回的html代码,删除标签中style中的背景颜色样式
                        var tempElement = document.createElement("div");
                        tempElement.innerHTML = this.detailData.contenttext;
                        var sectionList = tempElement.getElementsByTagName("*");
                        for (var i = 0; i < sectionList.length; i++) {
                            var style = sectionList[i].getAttribute("style");
                            if (style) {
                                style = style.replace(/background-color:[^;]+;/g, "");
                                sectionList[i].setAttribute("style", style);
                                // 设置img标签的样式
                                var imgList = sectionList[i].getElementsByTagName("img");
                                for (var j = 0; j < imgList.length; j++) {
                                    imgList[j].style.width = "100%";
                                    imgList[j].style.height = "auto";
                                }
                                // 设置文字颜色 包括但不限于p标签、span标签
                                var colorList = sectionList[i].getElementsByTagName("*");
                                for (var j = 0; j < colorList.length; j++) {
                                    if (colorList[j].style) {
                                        colorList[j].style.color = "#fff";
                                    }
                                }
                            }
                        }
                        this.detailData.contenttext = tempElement.innerHTML;

去除样式 去除后台返回html中样式


扫描二维码,在手机上阅读
收到2条评论
avatar
六思逸 8 个月前
学到了,感谢分享!
回复
avatar
爱你的东子 10 个月前
又学到了一片,我要把你吸干
回复