html - 来自动态 HTML 属性或类的 CSS 值以避免内联样式?

标签 html css attributes

众所周知,内联样式不是好的做法,它们与例如不兼容。 Content Security Policy .

这就是我想要在没有内联样式的情况下实现的:

<?php
$spacer_height = 390; // this is a dynamic value from user input could be any integer
?>
<div class="spacer" style="height:<?php echo $spacer_height; ?>"></div>

这就是我想要的:

HTML:

<?php
$spacer_height = 390; // this is a dynamic value from user input
?>
<div class="spacer spacerheight-<?php echo $spacer_height; ?>" data-height="<?php echo $spacer_height; ?>"></div>

外部样式表:

.spacer {
  height: spacer_height + "px"; // this line is dummy code
}

是仅使用 CSS 实现此目的的方法。没有JavaScript。没有 Polyfill。

我已经找到的是这个 5 年前的问题:CSS values using HTML5 data attribute

但是同时有解决方案还是有不使用属性的CSS解决方案?至少有整数的解决方案吗?

编辑:如果没有其他解决方案,即使是有效的 polyfill 也可能是一个受欢迎的答案。

最佳答案

因为你不能只做这个 CSS(但是,因为 attr() 函数只返回字符串值),这里是一个简单的脚本,它会做一些类似于 attr( ) 会,尽管这会解析数据并使用 cssText 对其进行动态设置。

如果我做对了请告诉我

window.addEventListener("load", function() {
    var mb = isMobile();
    var el = document.querySelectorAll('[data-css]');
    for (i = 0; i < el.length; i++) {
        var what = el[i].getAttribute('data-css');
        if (what) {
            what = what.split(',');
            el[i].style.cssText = what[0] + ': ' + ((mb) ? what[2] : what[1]) + 'px';
        }
    }
});

function isMobile() {
  //function that check if user is on mobile etc.
  return false;  // return false for this demo
}
html, body {
  margin: 0;
}

div {
    background-color: lightgreen;
    padding: 10px 0;
    height: auto;
    box-sizing: border-box;
}

div ~ div {
    margin-top: 10px;
}
<div data-css="height,60,30"></div>
<div></div>
<div></div>
<div data-css="height,60,30"></div>
<div></div>

另一种选择是在服务器端运行一些东西,您只需在其中创建 CSS 规则和类并将其分别插入 CSS 文件和标记,然后再发送到客户端

关于html - 来自动态 HTML 属性或类的 CSS 值以避免内联样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42630348/

相关文章:

html - 使遮光 div 拉伸(stretch)到其顶部 div 高度的 100%

html - Bootstrap Tabbable 问题

html - 使用带有内联 block 的列宽的最少两行

c# - ASP.NET MVC 显示没有时间的日期

c# - 了解 linq 中使用的 xml 命名空间

javascript - "Score"变量没有改变

javascript - 动态填充html中的json数据

javascript - 防止基于页面上现有的另一个类的默认点击操作

javascript - 根据子事件查找父元素

c# - GetCustomAttributes 继承参数与 AttributeUsage.Inherited