简体   繁体   English

当我使用Javascript单击导航菜单链接时,如何更改页面的背景图像?

[英]How can i change background image of the page when i click on navigation menu link using Javascript?

How can i change Background-image of the page when i click on navigation link using JavaScript ? 当我使用JavaScript单击导航链接时,如何更改页面的背景图像?

<li><a href="#"id="bd"onclick ="one()">facial</a></li>

<script>
 function one(){
   document.getElementById('bd').style.background-image=url(eye.jpg);
   }
</script>

Background image can be update with backgroundImage and the value should be string so wrap it with quotes. 可以使用backgroundImage更新背景图像,并且该值应为字符串,因此请用引号将其包裹起来。

 <li><a href="#" id="bd" onclick="one()">facial</a> </li> <script> function one() { document.getElementById('bd').style.backgroundImage = 'url(eye.jpg)'; } </script> 


Also you can simplify the code by passing the element reference. 您也可以通过传递元素引用来简化代码。

 <li><a href="#" id="bd" onclick="one(this)">facial</a> </li> <script> function one(ele) { ele.style.backgroundImage = 'url(eye.jpg)'; } </script> 

You could set up a class with the background image and then just add that class with JavaScript: 您可以使用背景图片设置一个类,然后使用JavaScript添加该类:

.eye {
   background-image: url(eye.jpg);
}

function one() {
   document.getElementById('bd').classList.add('eye');
}

That way you can also do any styling you need to do with the image. 这样,您还可以对图像进行任何样式设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用JavaScript更改当前页面的导航按钮/链接的背景颜色? - How can I change the background color of a current page's navigation button/link using JavaScript? 选择导航菜单链接时如何更改背景图像和文本 - How can I change background images and text on navigation menu link when it’s selected 当我将鼠标悬停在用作主页菜单链接的图像上时,如何更改背景 - How to change a background when i hover over an image being used as a menu link on the home page 单击带有BxSlider的链接时如何更改图像? - How can I change an image when I click a link with BxSlider? 单击颜色时如何更改背景图像? - how can I change the background image when I click on a color? 如何使用JavaScript将文本菜单链接更改为图像? - How can I change a text menu link to an imge using JavaScript? 如何使用链接更改背景图片 - How can I change the background image with a link 当我单击链接时如何使用javascript在CSS中更改图像中的选定颜色 - when i click link how to change selected color in image in css using javascript 仅使用 Javascript 单击导航菜单选项时,如何使导航菜单选项更改颜色或背景? - How Do I make my Nav Menu option change color or background when I click on it using Javascript only? 如何链接到使用 javascript 进行导航的页面的这个区域? - How can I link to this area of a page that uses javascript for navigation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM