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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21094583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:02:20  来源:igfitidea点击:

How change background image with javascript onClick on a link

javascriptjqueryhtmlcssbackground-image

提问by Sanjok Gurung

I want a background image to change with the onclick attribute on html link tag. But its not working.

我想要一个背景图像随着 html 链接标签上的 onclick 属性而改变。但它不工作。

<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. I have checked the directory where the images are they are correct. and I havent defined any background image on my css so. I need help and its driving me crazy.

如您所见,我尝试在 onclick 属性上传递一个函数,并且我已经在底部定义了这些函数,但背景图像仍然不会改变。我已经检查了图像正确的目录。我还没有在我的 css 上定义任何背景图像。我需要帮助,这让我发疯。

回答by PlantTheIdea

A couple things:

一些事情:

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

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=声明的需要。

回答by Gjohn

You have an href along with the click. You will need to specify your link as

你有一个href和点击。您需要将链接指定为

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

You will need to redirect to the page through 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?

您将需要通过 javascript 重定向到该页面。否则,您本质上是要求它将您重定向到 URL 并调用您的 javascript,但如果发生重定向,您将如何查看 javascript 执行产生的结果?

回答by Sergio

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 liyou 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

关于您拥有的链接,如果您想使用它们

回答by RDK

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)');
  });
});

回答by Oleg

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;
}

回答by ottis

I would always try to keep the image src decision out of the code, and move it into the CSS file. Something like:

我总是尝试将图像 src 决定排除在代码之外,并将其移动到 CSS 文件中。就像是:

// 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

这样当你想更新 srcs 或样式时,你不必去搜索 src

p.s. I haven't run the code above, but hopefully you get the idea :)

ps我还没有运行上面的代码,但希望你能明白:)