仅将特定元素添加到 html 正文中,具体取决于 javascript 条件

Add only specific element to html body depending on javascript condition

本文关键字:取决于 条件 javascript 正文 html 元素 添加      更新时间:2023-09-26

我正在学习使用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() 方法。你需要把地图放在一个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);