gpt4 book ai didi

javascript - 根据 javascript 条件仅将特定元素添加到 html 正文

转载 作者:太空宇宙 更新时间:2023-11-04 12:29:59 24 4
gpt4 key购买 nike

我正在学习使用 Apache Cordova 创建应用程序。根据手机屏幕的大小,我想创建一个具有特定宽度/高度的 div 元素以在其中显示谷歌地图。使用 javascript if/else 循环我设置了 css 样式首选项(宽度、高度等)。但是我怎样才能只显示一个带有样式首选项的 div 元素,从 javascript 到 HTML>

一些代码片段。这是为不同的占位符设置样式

#mapPlaceholder4S {
height: 200px;
width: 200px;
margin-top:20px;
margin-bottom:20px;
}

#mapPlaceholder5S {
height: 280px;
width: 280px;
margin-top:20px;
margin-bottom:20px;
}

这是决定使用哪个元素

if (screen.availHeight < 481) {
alert("4S detected");
map = new google.maps.Map(document.getElementById("mapPlaceholder4S"), mapOptions);
} else if (screen.availHeight > 481 && screen.availHeight < 569) {
map = new google.maps.Map(document.getElementById("mapPlaceholder5S"), mapOptions);
}

如何根据执行的条件只将一个占位符附加到我的 html 正文中。我对 HTML 和 CSS 技术还很陌生。我尝试使用 javascript 中的 appendChild 方法,但无法正常工作

最佳答案

您可以在 JavaScript 中使用 setAttribute() 和 removeAttribute() 方法。 您需要将 map 放在一个 div 中。给出“googleMap”的 div 和 id。

就像:

<div id="googleMap"  style="width:500px;height:380px;"></div>

然后,您可以执行以下操作:

就像:

.mapPlaceholder4S {
height: 200px;
width: 200px;
margin-top:20px;
margin-bottom:20px;
}
.mapPlaceholder5S {
height: 280px;
width: 280px;
margin-top:20px;
margin-bottom:20px;
}



if (screen.availHeight < 481) {
alert("4S detected");
document.getElementById("googleMap").setAttribute("id", "mapPlaceholder4S");
}
else if (screen.availHeight > 481 && screen.availHeight < 569) {
document.getElementById("googleMap").setAttribute("id", "mapPlaceholder5S");
}

map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);

关于javascript - 根据 javascript 条件仅将特定元素添加到 html 正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27736853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com