简体   繁体   English

如何使用javascript onClick更改背景图片的链接

[英]How change background image with javascript onClick on a link

I want a background image to change with the onclick attribute on html link tag. 我希望背景图片使用html链接标签上的onclick属性进行更改。 But its not working. 但是它不起作用。

<ul>
    <li><a href="index.php?page=Home" onclick="one();">Home</a> </li>
    <li><a href="index.php?page=Achivement" onclick="two();">Achivement</a></li>

    <li><a href="index.php?page=Career" onclick="three();">Career</a></li>
    <li><a href="index.php?page=Message" onclick="four();">Message</a></li>
    <li><a href="index.php?page=opportunity">opportunity</a></li>
    <li><a href="upload1.php">Register</a>
    <li></li>
 </ul>
  <script type="text/javascript">
  function one(){

 $('body').css('background-image','url(image/back1.jpg)');

}
function two(){

   $('body').css('background-image','url(image/back2.jpg)');

}
function three(){


}
function four(){


}  </script>

as you can see I tried passing a function on the onclick attribute and I have already defined these function on the bottom already and still the background image wont change. 如您所见,我尝试在onclick属性上传递函数,并且我已经在底部定义了这些函数,但背景图像仍然不会改变。 I have checked the directory where the images are they are correct. 我检查了图像正确的目录。 and I havent defined any background image on my css so. 而且我还没有在CSS上定义任何背景图片。 I need help and its driving me crazy. 我需要帮助,这使我发疯。

A couple things: 几件事:

  1. You need to include the jQuery library (in case you did not already) 您需要包括jQuery库(以防您尚未)
  2. You need to prevent the default action because it is a link 您需要阻止默认操作,因为它是一个链接
  3. You need to functionalize it for reuse. 您需要对其进行功能化以供重复使用。

Example: 例:

<script type="text/javascript">
    $(function(){
        $('a').on('click',function(e){
            var href = this.href.split('='),
                img;

            // prevents following to the link location
            e.preventDefault();

            // determines which background image
            switch(href[1]){
                case 'Home':
                   img = 'back1.jpg';
                   break; 
                case 'Achievement':
                   img = 'back2.jpg';
                   break;
                case 'Career':
                   img = 'back3.jpg';
                   break;
                case 'Message':
                   img = 'back4.jpg';
                   break;
                case 'Opportunity':
                   img = 'back5.jpg';
                   break;
            }

            // assigns background-image
            $('body').css({backgroundImage:'url(image/'+img+')'});
        });
    });
</script>

This will allow great reuse, and eliminate the need for the inline onclick= declarations. 这将允许大量重用,并且不需要内联onclick=声明。

You have an href along with the click. 点击的同时带有href。 You will need to specify your link as 您需要将链接指定为

<li><a href="#" onclick="one();">Home</a> </li>

You will need to redirect to the page through javascript. 您将需要通过javascript重定向到该页面。 Otherwise you are in essence asking it to go to redirect you to the URL and call your javascript but if the redirect happens how would you even see what the javascript execution yields? 否则,您本质上是在要求它去将您重定向到URL并调用您的javascript,但是如果发生重定向,您怎么会看到javascript执行的结果呢?

Remove your inline script and all your functions and try this instead: 删除内联脚本和所有函数,然后尝试以下操作:

$(function () {
    $('ul li a').on('click', function (e) {
        e.preventDefault)();
        $('body').css('background-image', 'url(image/back' + $(this).closest('li').index() + '.jpg)');
    });
});

If you just want to target the first 4 li you can add to my code a if($(this).closest('li').index() < 5){ change background }; 如果您只想定位前4 li ,则可以在我的代码中添加if($(this).closest('li').index() < 5){ change background };

About the links you have, if you want to use them 关于您拥有的链接(如果要使用它们)

Try to use this stetment for jQuery element: 尝试将此方法用于jQuery元素:

$(function() {
  $('elementLink').on('click', function(e){
       e.preventDefault();
       $('body').css('background-image','url(image/back1.jpg)');
  });
});

It should be like this: 应该是这样的:

onclick="one(); return false;"

when you click a link, the new page loads, so you have to prevent this behavior by writing return false 当您单击链接时,将加载新页面,因此您必须通过编写return false来防止此行为

You can also write 你也可以写

onclick="return one();"

and javascript: 和javascript:

function one(){
  $('body').css('background-image','url(image/back1.jpg)');
  return false;
}

I would always try to keep the image src decision out of the code, and move it into the CSS file. 我将始终尝试将image src决策保留在代码之外,并将其移入CSS文件。 Something like: 就像是:

// could be good to keep your url params as lower case as a convention, then this
// options object could be skipped and you'd just use the param as the classname
var options = {
  'Home': 'home',
  'Achievement': 'achievement'
};

$("ul li a").click(function(e){
  e.preventDefault();

  var href = $(this).attr("href");

  if(href[1])
  {
    $("body").addClass(options[href[1]]);
  }

});

then in your css file 然后在你的css文件中

body.achievement
{
  background: url("/images/some_img.png");
}

body.home
{
  background: url("/images/some_img2.png");
}

That way when you want to update the srcs, or styles, you do't have to go searching through the src 这样,当您要更新src或样式时,就不必搜索src了

ps I haven't run the code above, but hopefully you get the idea :) ps我还没有运行上面的代码,但希望您能明白:)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM