Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript或jQuery生成CSS媒体查询_Javascript_Jquery_Css_Media Queries - Fatal编程技术网

使用javascript或jQuery生成CSS媒体查询

使用javascript或jQuery生成CSS媒体查询,javascript,jquery,css,media-queries,Javascript,Jquery,Css,Media Queries,是否可以使用Javascript或jQuery动态创建完整的媒体查询规则? 我使用了大量的媒体查询,以使用内嵌CSS、导入和链接文件的通用视口和特定设备/屏幕为目标: @media screen and (min-width:400px) { ... } @import url(foo.css) (min-width:400px); <link rel="stylesheet" type="text/css" media="screen and (min-width: 400px)" hr

是否可以使用Javascript或jQuery动态创建完整的媒体查询规则?

我使用了大量的媒体查询,以使用内嵌CSS、导入和链接文件的通用视口和特定设备/屏幕为目标:

@media screen and (min-width:400px) { ... }
@import url(foo.css) (min-width:400px);
<link rel="stylesheet" type="text/css" media="screen and (min-width: 400px)" href="foo.css" />
我还研究了
document.stylesheets
和看似过时的特定于浏览器的:

  document.styleSheets[0].insertRule("p{font-size: 20px;}", 0)
但我找不到任何关于程序生成的参考:

  @media screen and (min-width:400px)

直接从javascript或以任何形式从javascript中删除。

您只需更新现有的
元素(或创建一个)
textContent
即可包含规则,这将使其在给定上下文中有效

document.querySelector('style').textContent +=
    "@media screen and (min-width:400px) { div { color: red; }}"

我用这种方式。这允许在文档中更新多个样式

在HTML中:

<style class="background_image_styles">
</style>

对于一般用途,您可以将样式表附加到
document.head
。然后你可以把任何你想要的mod放进去——包括媒体查询。由于它是
document.head
中的最后一个样式表,因此它会覆盖任何以前的CSS规则

香草JavaScript:

let style=document.getElementById('custom-style');
如果(!样式){
style=document.createElement('style');
style.id=“自定义样式”;
document.head.appendChild(样式);
}
style.innerHTML=
“@媒体屏幕和(最小宽度:400px){…}”;

只需更新现有的
样式
元素的内容就可以了:你的意思是添加css媒体查询规则吗?@ExplosionPills非常完美,是一个有价值的“答案”
$('style')。text(@media(最小宽度:400px){div{color:red;})
@MuhammadUmer将覆盖样式元素的全部内容,而不是附加到it@MuhammadUmer
.append
不追加文本内容,而是追加元素。如果参数是字符串,jQuery将尝试选择元素,并将阻塞
@
,但它也会添加文本,但更安全的方法是这样做
$('p')[0]
<style class="background_image_styles">
</style>
$(".background_image_styles").text("@media (min-width: 1200px) {.user_background_image{background-image: url('https://placehold.it/1200x300');}}");