【问题标题】:Add only specific element to html body depending on javascript condition根据javascript条件仅将特定元素添加到html正文
【发布时间】:2015-01-02 02:49:51
【问题描述】:

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

一些代码sn-ps。 这是为不同的占位符设置样式

#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 方法,但无法使其正常工作

【问题讨论】:

  • 为什么不使用带有 ID 或 CLASS 的单个 &lt;div&gt;,然后使用 CSS @media 查询(允许您指定大小以更改关联 ID 或 CLASS 的 CSS
  • 如果您尝试显示相对于屏幕尺寸的宽度,您可以使用百分比而不是像素

标签: javascript html css


【解决方案1】:

您可以在 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);

【讨论】:

  • setAttribute 将返回undefined,因此您将把undefined 传递给google.maps.Map。您需要获取元素,将属性设置在单独的行上,然后使用该元素调用Map
  • 我编辑了我的答案。对不起。首先,您需要在 DOM 对象上调用 setAttribute() 方法。然后你可以实例化新的 google.maps.whatever() 对象。
  • 为了进一步调整,为什么不一开始就调用getElementById一次,然后根据条件设置它的属性,然后调用new google.maps.Map一次呢?
猜你喜欢
  • 2021-07-03
  • 2022-10-14
  • 2022-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
  • 2012-05-05
  • 1970-01-01
相关资源
最近更新 更多