当涉及到在浏览器上的加载、浏览器支持以及我可能没有想到的任何事情等方面。在 Javascript 中声明绝大多数或全部样式是否会伤害最终用户而不是包含 CSS 样式表?
我拼凑了一个简单的例子,如下所示,还有这个Fiddle
HTML:
<body onload="init();">
<div class="container">
<div class="row">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>
<div class="row">
<div class="col"></div>
<div class="col"></div>
</div>
</div>
</body>
Javascript:
var init = function() {
// Using window object to set global variables
// since global variables are attached to the window object anyway
window.container = document.getElementsByClassName("container");
window.row = document.getElementsByClassName("row");
// Initialize variables
window.rows = [];
window.cols = [];
// Get chidren counts but also setup for future use
window.setCounts();
// Now lets calculate the widths
window.setWidths();
};
window.setCounts = function() {
for (var c = 0; c < window.row.length; c++) {
window.rows.push(window.row[c]);
window.rows[c].row_count = 0;
for (var i = 0; i < window.row[c].children.length; i++) {
if (window.row[c].children[i].className === 'col') {
window.rows[c].row_count += 1;
}
}
}
};
// When the screen is resized we need to refactor the widths
window.onresize = function(event) {
window.setWidths();
};
window.setWidths = function() {
window.wWidth = window.innerWidth;
window.wHeight = window.innerHeight;
var container_width = window.wWidth * 0.95;
var row_width = container_width * 0.98;
for (var i = 0; i < window.container.length; i++) {
window.container[i].style.width = (window.wWidth * 0.97) + "px";
window.container[i].style.height = ((window.wHeight * 0.90)) + "px";
}
for (var c = 0; c < window.rows.length; c++) {
window.rows[c].style.width = row_width + "px";
for (var i = 0; i < window.rows[c].children.length; i++) {
if (window.rows[c].children[i].className === 'col') {
window.rows[c].children[i].style.width = (row_width / window.rows[c].row_count) + "px";
window.rows[c].children[i].innerText = (row_width / window.rows[c].row_count) + "px";
}
}
}
};
最后是 CSS(临时的,考虑在 Javascript 中应用所有样式):
div {
overflow: hidden;
}
.container {
margin: auto;
margin-top: 5px;
border: 1px solid red;
}
.row {
margin: auto;
margin-top: 5px;
border: 1px solid black;
clear: both;
}
.col {
float: left;
text-align: center;
}
请注意:
我想避免实现像 JQuery 这样的外部库,我知道我上面的代码使用 JQuery 会更容易完成。到目前为止,我已将我的外部库限制为 AngularJS,因为它是应用程序的主干,这可以减少我的 web 应用程序中的升级和可能的中断。这是一个偏好和长寿的问题(在我看来),请避免试图说服我。