javascript - 尝试使用 javascript 和媒体查询更改边距

标签 javascript html css

伙计们,这是一个简单的日历,我想使用 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)')

Reference link

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/

相关文章:

Javascript - 对象数组,对象包含另一个数组和一个 int

javascript - 当另一个日期发生更改时,JQuery UI Datepicker 重新启动

javascript - jquery - 设置 iframe 宽度不起作用

javascript - _0_ 放在 &lt;script&gt; 标签中 js 文件的源路径末尾时是什么意思

javascript - 拖放 jquery 不工作

javascript - 从 IP 字符串计算 IP 范围等于 x.x.x.x/x

html - 停止在页面加载时触发 CSS 转换

html - 如何应用缩放效果,但不在悬停时

css - Android webview ':active' 在元素处于事件状态时隐藏时保持打开状态

javascript - 没有滚动条的 DIV [HTML | CSS | JavaScript]