我有代码,可以在应用程序端动态地将自定义 css 添加到我的 html 中,如下所示:
C# 代码:
html = html + string.Format("<div id='{0}' class='sectioncon SectionComp
responsiveSectionClass_{0}'>", sectionGUID);
这个 html 变量返回到 UI,然后我使用 (someselector).append(html)
然后客户端我检索此信息并使用 jquery 吐出媒体查询,如下所示:
Jquery 代码:
var stylesheetXS = $("<style id='" + this.responsiveClass + "'>")
var txtAll = "";
txtAll += "@@media screen and (max-width : 480px) {";
txtAll += "." + this.responsiveClass;
txtAll += "{";
txtAll += this.Style;
txtAll += "}";
txtAll += "}";
$(stylesheetXS).html(txtAll);
$("head").append(stylesheetXS);
因此,this.responsiveClass 是对responsiveSectionClass_{0} 的引用,其中 {0} 是 GUID。
在将 C# 代码附加到 UI 之前,首先添加 Jquery 代码,那么为什么我的动态生成的媒体查询不会影响 html 代码中的类?
此外,当我使用 Chrome 开发人员工具选择元素时,我看不到已生成的媒体查询,这就是为什么我认为我在这里做错了什么。
这是生成的 html 或其一部分:
媒体查询:
@media screen and (max-width : 480px) {.responsiveSectionClass_d7099673a3924894bec0bdb59f6ad0b0{padding-top:30px;padding-bottom:30px;width:auto;height:auto;}}
HTML:
<div class="sectioncon SectionComp responsiveSectionClass_d7099673a3924894bec0bdb59f6ad0b0" style="padding-top:30px;padding-bottom:30px;width:auto;height:auto;"></div>
这就是我在代码检查器中看到的所有内容:
element.style {
padding-top: 30px;
padding-bottom: 30px;
width: auto;
height: auto;
}
.sectioncon {
padding-top: 30px;
padding-bottom: 30px;
width: auto;
height: auto;
}
对于内森的回应,我尝试了这个:
var txtAll = "";
txtAll += "@@media screen and (max-width : 480px) {";
txtAll += "." + this.responsiveClassXS;
txtAll += "{";
txtAll += this.Style;
txtAll += "}";
txtAll += "}";
var css;
css = document.createElement("style");
css.id = this.responsiveClassXS
css.type = 'text/css';
css.media = "all";
css.textContent = txtAll;
document.getElementsByTagName("head")[0].appendChild(css);
但仍然无法识别媒体查询。
最佳答案
出于某种原因,我无法让它在堆栈片段中工作,但您可以查看实时演示 here (或者只是将下面的代码保存为 .html 文件并在浏览器中打开它......)我将背景设置为蓝色,以便它更加突出......
这是此工作的视频:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
</body>
<script>
let iframeEl = document.createElement("iframe");
iframeEl.setAttribute("style", "height: 100%; width: 100%;");
document.body.appendChild(iframeEl);
iframeEl.contentDocument.open();
iframeEl.contentDocument.write('<div class="sectioncon SectionComp responsiveSectionClass_d7099673a3924894bec0bdb59f6ad0b0" style="padding-top:30px;padding-bottom:30px;width:auto;height:auto;"></div>');
iframeEl.contentDocument.close();
let styleSheet = `
@media only screen and (max-width : 480px) {
.responsiveSectionClass_d7099673a3924894bec0bdb59f6ad0b0 {
padding-top: 30px;
padding-bottom:30px;
width:auto;
height:auto;
background-color: blue;
}
}`;
let style = '<style type="text/css">' + styleSheet + "</style>";
iframeEl.contentDocument.head.innerHTML += style;
</script>
</html>
关于javascript - 动态地将媒体查询添加到页面并覆盖从应用程序端生成的 html 中的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59549339/