将@media标签动态绑定到元素

Binding @media tag dynamically to element

本文关键字:元素 动态绑定 标签 @media      更新时间:2023-09-26

我用javascript代码创建了所有的html/css:

var el = document.createElement('div');
el.setAttribute('id', 'fooBar');
el.style.width = "30%";
document.getElementById('body').appendChild(el);

一切正常,但现在我想添加@media标签到该代码。整个html/css代码被附加到body元素,所以最好不要使用id或类。

我找到的唯一解决方案是:

document.querySelector('style').textContent += 
    "@media screen and (max-width: 1280px) { fooBar { font-size: 11px; }}";

但这是不好的,因为它搞砸了外部样式,我宁愿做本地。此外,它似乎不适用于动态创建的样式,如宽度或高度。

如何解决这个问题?

你可以直接检查屏幕的大小。
然后根据屏幕大小应用样式。
可能还需要将它与屏幕大小调整事件挂钩。

function sizeStyle() {
  if (screen.width >= 900) {
    [your javascript styles here]
  } else if (screen.width >= 600) {
    [other javascript style]
  }
}
window.onresize = function(event) {
  sizeStyle();
}; //resizing the window
sizeStyle(); //(before dom?) initial call