使用js和jq无法切换display效果,但是用alert有获取到div的display
<li>
<botton class="social-custom" style="cursor:pointer;" onclick="openwechat()">
<img src="//cdn.shopify.com/s/files/1/0520/6396/1266/files/wechat.png?v=1675139232">
botton>
li>
<div id="wechatdiv" style="display:none;">
<botton style="cursor:pointer;" onclick="closewechat()"><img src="https://img.icons8.com/material-outlined/15/null/delete-sign.png">botton>
<img src="//cdn.shopify.com/shopifycloud/shopify/assets/no-image-100-c91dd4bdb56513f2cbf4fc15436ca35e9d4ecd014546c8d421b1aece861dfecf_small.gif">div>
<script>
function openwechat(){
var showWechat = document.getElementById("wechatdiv").style.display;
if (showWechat = "none") {
document.getElementById("wechatdiv").style.display = "block";
} else {
document.getElementById("wechatdiv").style.display = "none";
}
}
function closewechat(){
var showWechat = document.getElementById("wechatdiv").style.display;
if (showWechat = "block") {
document.getElementById("wechatdiv").style.display = "none";
}
}
script>
页面上出现了2个id为wechatdiv的容器,首先出现的是页头移动端的,然后才是页脚的wechatdiv,而document.getElementById("wechatdiv")只会得到第一个出现(就是页头的wechatdiv),而页头的wechatdiv的容器只有在移动端并且展开菜单后才会显示。所以pc端点击页脚的openwechat实际控制的移动端的openwechat,导致页脚的wechatdiv无法显示。
改为属性选择,函数改成下面即可
function openwechat() {
var els = document.querySelectorAll('div[id="wechatdiv"]');//改为属性选择器
for (var el of els) el.style.display = el.style.display == 'block' ? 'none' : 'block';
}
function closewechat() {
//因为是关闭,不需要再判断了
var els = document.querySelectorAll('div[id="wechatdiv"]');//改为属性选择器
for (var el of els) el.style.display = 'none' ;
}
这里的if语句要用==判断,一个=是赋值。if (showWechat == "none")
=是赋值,要用比较运算符==或者===:
function openwechat() {
var showWechat = document.getElementById("wechatdiv").style.display;
if (showWechat === "none") {
document.getElementById("wechatdiv").style.display = "block";
} else {
document.getElementById("wechatdiv").style.display = "none";
}
}
function closewechat() {
var showWechat = document.getElementById("wechatdiv").style.display;
if (showWechat === "block") {
document.getElementById("wechatdiv").style.display = "none";
}
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!