伙计们,这是一个简单的日历,我想使用 javascript 更改 margin-left 属性。我使用简单的 javascript 代码。这是一个完整的演示:http://buhehe.de/kalender-2018/
<script>
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
var table = document.getElementsByClassName("calendar");
var newmargin = (x - 222)/2;
var mq = window.matchMedia('@media all and (max-width: 500px)');
if( mq.matches) {
table.style.marginLeft = "newmargin ";
}
</script>
日历宽度为 222px。我的目标是将它们设置在 Mobile 的中心。所以我尝试获取第一个移动屏幕宽度,然后我减去 222px 并将其除以 2。这必须是一个 margin-left 值。 但这并没有改变什么
最佳答案
你必须对你的代码做一些改变,比如
table.style.marginLeft = "newmargin";
到
table.style.marginLeft = newmargin +"px";
和
window.matchMedia('@media all and (max-width: 500px)')
到
window.matchMedia('all and (max-width: 500px)')
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight || g.clientHeight;
var table = d.getElementsByClassName("calendar")[0];
var newmargin = (x - 222) / 2;
console.log(newmargin+"px")
var mq = window.matchMedia('all and (max-width: 700px)');
if (mq.matches) {
table.style.marginLeft = newmargin +"px";
}
.calendar{width:222px;height:40px;background:red;}
<div class="calendar"></div>
希望对你有帮助
关于javascript - 尝试使用 javascript 和媒体查询更改边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48129337/