所以我想使用 js 获取 .SideArrow 的边距顶部(因为它是响应式的并使用 calc()),并使用菜单向其添加一个小像素值,但前提是 .SideArrow 具有“显示:内联 block ” .它通常是“显示:内联”,但随着媒体查询而改变。
我认为“If it's display: inline”部分已记下(尚未将其应用到函数中)。问题是获取 margin-top
我已经尝试了您在代码中看到的内容,并简单地添加
var margin = document.getElementsByClassName("SideArrow").style.marginTop;
我遇到的问题是它总是响应: 未捕获的类型错误:无法在“窗口”上执行“getComputedStyle”:参数 1 不是“元素”类型。 在(索引):80
指数:80 var style = window.getComputedStyle(arrows);
代码:
var objName = "SideArrow";
//Function to toggle menu
var nav = document.getElementById("MobileNav");
var menubtn = document.getElementById("MobileMenu");
var arrows = Array.prototype.slice.call(document.querySelectorAll("." + objName));
var margin = arrows.map(x => x.style.marginTop);
console.log(margin); //Both output []
console.log(arrows);
alert(margin); //Doesn't alert anything
var mvalue = arrows.rules.marginTop;
var tvalue = 197;
var zvalue = mvalue + tvalue;
console.log(mvalue);
function MenuToggle() {
if (arrows.some(x => x.style.display == objProperty) && nav.style.height === "197px") {
nav.style.height = "0px";
menubtn.innerHTML = "menu"; //Using Material icons for now
arrows.style.marginTop = "mvalue" + "px";
}
else if (arrows.some(x => x.style.display == objProperty) && nav.style.height === "0px") {
nav.style.height = "197px";
menubtn.innerHTML = "clear";
arrows.style.marginTop = "zvalue" + "px";
}
else if (arrows.some(x => x.style.display != objProperty) && nav.style.height === "197px") {
nav.style.height = "0px";
menubtn.innerHTML = "clear";
arrows.style.marginTop = "mvalue" + "px";
}
else {
nav.style.height = "197px";
menubtn.innerHTML = "clear";
arrows.style.marginTop = "mvalue" + "px";
}
如代码所示,我希望 toe margin-top 在函数运行时向其添加 197 像素,高度为“nav”(仅当显示为内联 block 时),但我什至无法获取当前 margin-top 正确。
更新: 更新了函数本身,也就是 *. 还有@JackBashord 向我展示的边距和箭头变量
编辑:
我设法解决了这个问题,并想出了一些其他的东西,对其他遇到同样问题的人感到抱歉。
我给每个箭头赋予了自己的 id,并用 margin-top
和 position: absolute
弄乱了。
祝你好运
最佳答案
问题是当您调用 getElementsByClassName
时,您得到的是一个 NodeList,它是一种数组,而不是单个元素。您可以改用 querySelector
来解决此问题:
var arrows = document.querySelector("." + objName);
而且您可以在不使用 getComputedStyle
的情况下获取 margin-top
值 - 只需这样做:
var margin = arrows.style.marginTop;
然后像这样执行你的函数:
if (arrows.style.display == "inline") {
MenuToggle();
}
注意:只有当只有一个 .SideArrow
元素时,以上内容才有效。以下是对多个元素执行此操作的方法:
var arrows = Array.prototype.slice.call(document.querySelectorAll("." + objName));
var margin = arrows.map(x => x.style.marginTop);
if (arrows.some(x => x.style.display == "inline") {
MenuToggle();
}
注意:以上将生成 margin
和 arrows
数组。
关于javascript - 我正在尝试获取此元素 margin-top 并简单地更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53964462/