javascript - 如何在加载时切换图像

标签 javascript html css

我想在 div(html 格式)中显示图像(来自 css id)。图像必须与模板匹配。每个用户都有不同的模板,因此他们需要在 body View 上显示不同的图像。

到目前为止,这是我的尝试:

HTML

<div id="logoHeader"></div>

CSS

    #logoheader_1 {
    height: 100px;
    background: url("/logoheader_1.png") left 20px no-repeat;
     }
   #logoheader_2 {
   height: 100px;
   background: url("/logoheader_2.jpg") left 20px no-repeat;
    }

JS

var templates = 1; // This is just example of if user A using template 1

switch(templates) {
  case '1'
    document.getElementById("logoHeader").onload = function() {
        document.getElementById("logoheader_1");
    };
  break;
  case '2'
    document.getElementById("logoHeader").onload = function() {
        document.getElementById("logoheader_2");
    };
  break;
}

jsfiddle

好吧,到现在为止还行不通。你能帮我看看如何在每个模板的 div 正文中显示正确的图像吗?

非常感谢。

最佳答案

所以,首先,您的 switch 语法是错误的,您试图将字符串与数字值(即 1'1')进行比较,但这并没有不能使用 switch 语句,因为它使用 strict equality

那么我建议你使用类而不是标识符来改变元素的样式。

最后,load 事件在 div 元素上不可用,所以我在窗口上调用它以确保 div 已加载并准备好用过。

window.addEventListener('load', function() {
  var templates = 1;

  switch (templates) {
    case 1:
      document.getElementById('logoHeader').classList.add('logoheader_1');
      break;
    case 2:
      document.getElementById('logoHeader').classList.add('logoheader_2');
      break;
  }
});
.logoheader_1 {
  height: 100px;
  background: red;
}

.logoheader_2 {
  height: 100px;
  background: black;
}
<div id="logoHeader"></div>

关于javascript - 如何在加载时切换图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44950901/

相关文章:

javascript - iPad 网络应用程序。 Javascript,加载所有内容还是切换页面?

css - 将类添加到 Angular 4 中的元素

javascript - Vim 中有自动压缩 CSS、Html 和 Javascript 代码的方法或插件吗?

html - 文本不会正确对齐到中心

javascript - react : Update state variables shorthand

javascript - 是否可以在 createMaterialBottomTabNavigator 中使用 createMaterialTopTabNavigator 的滑动过渡?

html - 纯 CSS 选择菜单/下拉菜单 : How to make custom right arrow?

javascript - React 路由器问题未捕获错误 : Invariant Violation: Element type is invalid: expected a string (for built-in components)

javascript - 是否可以在同一页面上使用两种不同的颜色框样式?

html - 我该如何提取这段文字