使用CSS或JavaScript更改背景图像一次

时间:2012-07-06 12:42:36

标签: javascript html css

我被朋友要求设置一个网页,当点击任何链接时,其背景只会改变一次。我已经尝试了一些在这个网站上给出的例子,并在谷歌上看了几个,但它们几乎都是画廊风格的周期性变化。也许我只是沮丧而没有看到森林的树木......

该页面是@ mysite / julie 图片是@ mysite / julie / images / blogbka.png和/images/blogbk.png

我使用了下面的解决方案(https://stackoverflow.com/a/11362465/1506620

谢谢大家的帮助。

6 个答案:

答案 0 :(得分:2)

var is=true;
document.body.onclick = function( e ) {
    if ( e.target.tagName === 'A' ) {
if(is){
document.body.style.background='url(http://adultdave.co.uk/julie/images/blogbka.png)';is=false;}
}
};

答案 1 :(得分:1)

我希望这就是你想要的,即只改变一次图像。如果没有,请告诉我。

var ischange=true;
document.onclick=function(e){
if( e.target.tagName === 'A' &&ischange)
{
document.body.style.background='url(/*Image url*/)';
ischange=false;
}
}

<强> DEMO

在每个页面上加载一个变量ischange初始化为true,当点击任何链接时,后台被更改并且ischange被设置为false,因此不再允许更改背景。

答案 2 :(得分:0)

一种方法是使用包装另一个函数的函数,仅在第一次调用时执行内部函数。这是一个非常通用的版本:

var once = function(fn, thisObj) {
    var called = false;
    var val;
    return function() {
        if (called) {return val;}
        called = true;
        val = fn.apply(thisObj || null, arguments);
        return val;
    };
};

然后,您可以将MooTools事件侦听器包含在对once()的调用中,并知道它只会被调用一次。对于这些问题,这可能是一个相当优雅的解决方案。

答案 3 :(得分:0)

我已经使用jQuery点击每个链接随机更改页面背景。 所以,请按照以下步骤操作:

1)在标题上包含最新的Jquery java脚本文件。

2)HTML:

 <div>
  <p>
    When you click on following paragraph link, every time it will be changed random background of the page
  </p>

  <p>
    You have a present that was really memorable. It could have been given for an 
    <a href="#">
      important occasion
    </a>
    or just for no reason at all. Tell us about the present and why it was memorable. Include the reason it was given, a 
    <a href="#">
      description
    </a>
    of it, and how you felt when you got it.

    The objective is to write a 
    <a href="#">
      narrative essay
    </a>
    about this present you were given

    The subject is a 
    <a href="#">
      memorable present
    </a>
    The three main subtopics are:
    <ul>
      <li>
        <a href="#">
          the reason it was given
        </a>
      </li>
      <li>
        <a href="#">
          a description of it and
        </a>
      </li>
      <li>
        <a href="#">
          how you felt when you got it
        </a>
      </li>
  </ul>
</p>
</div>

CSS:

body{
  background:url("http://www.freeppt.net/background/modern-pink-floral-backgrounds-for-powerpoint.jpg");
}

JQuery的:

var items = new Array();
items[0] = "http://www.publicdomainpictures.net/pictures/10000/nahled/abstract-orange-background-29541280675430Trj9.jpg";
items[1] = "http://www.psdgraphics.com/wp-content/uploads/2011/03/red-flowing-background.jpg";
items[2] = "http://www.dvd-ppt-slideshow.com/images/ppt-background/background-3.jpg";
items[3] = "http://www.purplebackgrounds.net/wp-content/uploads/2011/10/purple-heart-background-680x544.jpg";
items[4] = "http://www.freeppt.net/background/beautiful-on-green-backgrounds-for-powerpoint.jpg";

$(function() {
    var bg_img = '',
        last_bg = '';
    $("a").click(function() {
        bg_img = items[Math.floor(Math.random() * items.length)];
        if (last_bg == bg_img) bg_img = items[Math.floor(Math.random() * items.length)];
        last_bg = bg_img;
        $("body").css('backgroundImage', 'url(' + bg_img + ')');
    });
});

http://codebins.com/codes/home/4ldqpbc

上试用DEMO

答案 4 :(得分:0)

正如我所看到的,您希望为用户的浏览器提供一个cookie来咀嚼并跟踪页面上所有锚标签的点击事件。你可以这样做:

Mock Html

<ul id="ActionLinks">
    <li><a href="#" class="tracked-click">Click Me!</a></li>
    <li><a href="#" class="action-clear-cookie">Clear Cookie!</a></li>
</ul>

jQuery代码

<script type="text/javascript">
    $(document).ready(function () {
        // Array to store options 
    var settings = {
        getRadomImage: function () {
            //Update this with your different images.
            var items = [
                "http://adultdave.co.uk/julie/images/blogbka.png",
                "http://adultdave.co.uk/julie/images/blogbka.png",
                "http://adultdave.co.uk/julie/images/blogbka.png", 
            ];
            var img = items[Math.floor(Math.random() * items.length)];
            return img;
        },
        cookieName: "tracker",
        cookieOpts: { expires: 1} //cookie plug-in options
    }

    //Capture all tracked clicks
    $(".tracked-click").click(function (e) {
        //Check to see if there is a cookie for the user.
        if ($.cookie(settings.cookieName) != "true") {
            var img = document.createElement('img');
            img.src = settings.getRadomImage();
            //Load up the new image and show it once it's loaded.
            img.onload = function () {
                //Fade out the body and fade back 
                /*
                $("body").fadeOut(function() {
                $(this).css({ 'background-image': 'url(' + img.src + ')' }).fadeIn(4000);
                });
                */
                $("body").css({ 'background-image': 'url(' + img.src + ')' });

            };
            //Set the cookie for the client for tracking.
            $.cookie(settings.cookieName, true);
        }
    });

        //Action for clearing cookie.
        $(".action-clear-cookie").click(function () {
            $.cookie(settings.cookieName, null)
        });
    });
</script>

代码参考

答案 5 :(得分:-1)

设置jQuery脚本:

$("a").click(function(evt) {
  $('body').css("background-image", "url(/myimage.jpg)");
}

如果您希望在页面之间进行更改,请使用会话cookie(我使用“更简单”的功能,请参阅(此)[http://jquery-howto.blogspot.fr/2010/09/jquery-cookies-例如getsetdelete-plugin.html]:

if (getCookie('isAlreadyVisited') == 1) {
   $('body').css("background-image", "url(/myimage.jpg)");
}
setCookie('isAlreadyVisited', 1);

你也可以通过在服务器端设置cookie并在你的身体上添加一个类来改变背景(你不会以这种方式使用Flash of Unstyles Content)来处理这个问题。

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

body.visited {
   background-image: url(img2.jpg);
}