简体   繁体   English

div onclick功能可以改变身体背景图像

[英]div onclick function to change body background image

I want a small picture that acts like a button, to be click-able with a function to change the body background-image. 我想要一个像按钮一样的小图片,可以点击一个功能来改变身体背景图像。 I am a total newbie and I'm trying to learn. 我是一个新手,我正在努力学习。 The most simple way, I thought, would be to have a div with a background-image . 我想,最简单的方法是使用带background-image的div。 I have to use unsemantic grid, also. 我也必须使用非语义网格。

So I pretty much only have the div with a background image. 所以我几乎只有背景图像的div。 How do I write this function? 我该如何写这个函数? I'm sure it's really easy and I've read like 20 threads here but none of them were useful for me 我确定这很简单,我在这里看了20个线程,但没有一个对我有用

Edit: added my code 编辑:添加了我的代码

 #knapp { height:50px; width:50px; background-image:url(http://ingridwu.dmmdmcfatter.com/wp-content/uploads/2015/01/placeholder.png); background-repeat:no-repeat; background-size:contain; position:absolute; top:90vh; right:3vw; } 
 <div id="knapp" class="grid-10 prefix-90"></div> 

Add cursor on the div to appear clickable 在div上添加光标以显示可点击

   #knapp {
      cursor: pointer;
   }

You could put the new background-image in a new css rule 您可以将新的背景图像放在新的css规则中

body.newbg {
    background-image:url(path-to-new-background.png);
}

This is body with the old background-image 这是旧背景图像的身体

body {
    background-image:url(path-to-old-background.png);
}

and with jquery just add/toggle the class by doing something like that (in $(document).ready() ): 并使用jquery通过执行类似的操作添加/切换类(在$(document).ready() ):

$('#knapp').on('click', function(){

    $('body').addClass('newbg');
    // you could instead do toggleClass if you want for each click to have background switch between old background and new background
});

This is a cleaner approach compared to all the other answers as it separates presentation (css), structure (html) and behavior (javascript). 与所有其他答案相比,这是一种更清晰的方法,因为它分离了表示(css),结构(html)和行为(javascript)。 This is because it doesn't use JavaScript to change style directly. 这是因为它不使用JavaScript直接更改样式。 Also it doesn't pollute html with onclick which is also a bad practice. 它也不会用onclick污染html,这也是一种不好的做法。

Here is a plunkr: https://plnkr.co/edit/aiGZmvvi6WWGFs7E9xTp 这是一个plunkr: https ://plnkr.co/edit/aiGZmvvi6WWGFs7E9xTp

and here is one with a circular collection of backgrounds (thanks to Kai's idea) https://plnkr.co/edit/0djmmNM9OOTdfYyvLvUH?p=preview 这里有一个圆形的背景集(感谢Kai的想法) https://plnkr.co/edit/0djmmNM9OOTdfYyvLvUH?p=preview

  1. Create a button with onclick attribute with a function name like replace . 创建一个带有onclick属性的按钮,其功能名称为replace
  2. Defined the function in your script like: 在脚本中定义了函数,如:

     function replace() { document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)'; } 

Explanation: 说明:

You set the style property of the body (using document.body object) to other background-image . 您可以将body的style属性(使用document.body对象)设置为其他background-image

If something is not clear, I will happy to explain. 如果事情不明确,我很乐意解释。

Working example: 工作范例:

 function replace() { document.body.style.backgroundImage = 'url(https://lh6.ggpht.com/8mgTDZXaLMS1JsnF28Tjh6dahHwN1FqcXCVnifkfppmNLqnD-mPBuf9C1sEWhlEbA4s=w300)'; } 
 body { background-image: url(http://www.julienlevesque.net/preview/google-smile-preview.jpg); } div { background:blue; color:#fff; float:left; } 
 <div onclick="replace()">Replace background-image</div> 

If I understand the question, you should be able to create a variable in jQuery which is an array of all the string versions of your image urls that you want to use: 如果我理解了这个问题,你应该能够在jQuery中创建一个变量,它是你想要使用的图像网址的所有字符串版本的数组:

var images = ['../images/####','../images/$$$$', 'http://some.other/url.here];

// do this for as many images as you want to cycle through

Like that. 像那样。

Then you can make a counter variable: 然后你可以创建一个计数器变量:

var counter = 0;

and set it to zero. 并将其设置为零。

Next, add the event listener on() to your div like this: 接下来,将事件监听器on()添加到div如下所示:

$('#knapp').on('click', function(){



});

Finally, inside your event listener, change the CSS background-image property of the div to one of your images in the array: 最后,在您的事件侦听器中,将div的CSS background-image属性更改为数组中的一个图像:

// do this inside a document.ready() function
$('#knapp').on('click', function(){

    $(this).css('background-image','url("' + images[counter] + '")');
    counter++;

});

I hope this helped! 我希望这有帮助! Also, remember to increment counter 另外,记得增加counter

EDIT ---------------------------------------------------------------- 编辑------------------------------------------------- ---------------

OK, so I totally jumped over something obvious which is the fact that the counter might go too high and access something out of scope. 好的,所以我完全跳过一些明显的事情,这个事实是计数器可能会过高并且访问超出范围的东西。 To prevent this add the following inside of your on() listener: 为了防止这种情况,在on()侦听器中添加以下内容:

if(counter >= images.length - 1){

    counter = 0;

}

EDIT 2 -------------------------------------------------------------- 编辑2 ------------------------------------------------ --------------

Ok, so I didn't know what exactly you were asking at first, so here is my second answer. 好的,所以我一开始并不知道你究竟在问什么,所以这是我的第二个答案。 Since it seems like what you are actually trying to do is only switch the background image once on click, then you could use something like this: 因为看起来你实际上想要做的只是在点击时切换一次背景图像,那么你可以使用这样的东西:

$(document).ready(function(){

    $('#knapp').on('click', function(){

        $(this).css('background-image','url("YOUR_NEW_URL_HERE")');

});

});

or you could have it toggle between two images by making two identical classes in CSS (except for the background image) and replacing one with the other using .addClass and .removeClass . 或者你可以通过在CSS中创建两个相同的类(背景图像除外)并使用.addClass.removeClass替换另一个来在两个图像之间切换。

EDIT 3--------------------------------------------------------------- 编辑3 ------------------------------------------------ ---------------

I never thought I would edit this post this many times, but apparently I missed that the body background image should be changed (thanks to comments). 我从没想过我会多次编辑这篇文章,但显然我错过了body背景图片应该改变(感谢评论)。 My bad and thanks for pointing it out (even if you were talking to someone else). 我很糟糕,感谢你指出(即使你和别人说话)。

This may help you... 这可能对你有所帮助......

$('.yourClassofDiv').click({
   $(this).css("background-image",'url("' + URLofIMAGE+ '")')
});

Try using onclick at div#knapp element , set document.body.style.background to url of image file 尝试在div#knapp元素上使用onclick ,将document.body.style.background设置为图像文件的url

 #knapp { height:50px; width:50px; background-image:url(http://lorempixel.com/50/50); background-repeat:no-repeat; background-size:contain; position:absolute; top:90vh; right:3vw; } 
 <div id="knapp" class="grid-10 prefix-90" onclick="document.body.style.background = 'url(http://lorempixel.com/'+ window.innerWidth + '/'+ window.innerHeight +') no-repeat'"></div> 

here is a simple way in jquery 这是jquery中的一种简单方法

 $(document).ready(function() { $("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat'); $('div').css('cursor', 'pointer').click(function() { $("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <body> <div style="background-color:yellow">Click Here to change background Image</div> </body> 

Here i will explain the code. 在这里,我将解释代码。 The jQuery syntax is tailor made for selecting HTML elements and performing some action on the element(s). jQuery语法是为选择HTML元素和对元素执行某些操作而量身定制的。

Basic syntax is: $(selector).action() 基本语法是: $(selector).action()

A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

Here is what happen in the code. 这是代码中发生的事情。

1. 1。

$(document).ready(function(){

   // jQuery methods go here...

}); 

This is to prevent any jQuery code from running before the document is finished loading (is ready).It is good practice to wait for the document to be fully loaded and ready before working with it. 这是为了防止任何jQuery代码在文档加载完成之前运行(准备就绪)。在使用文档之前等待文档完全加载并准备就绪是一种好习惯。 This also allows you to have your JavaScript code before the body of your document, in the head section. 这也允许您将JavaScript代码放在文档正文之前的head部分中。

2 2

$("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/detail-requiem.jpg)').css('background-repeat', 'no-repeat');

getting the body element of your html and set its background-image with .css() action. 获取html的body元素并使用.css()动作设置其背景图像。 which i gave it more one action 我给了它更多的一个动作

3 3

$('div').css('cursor', 'pointer').click(function() {
        $("body").css('background-image', 'url(http://julienlevesque.net/Requiem/images/Requiem-Julien-Levesque.jpg)');
    });

this is where the change takes place. 这是发生变化的地方。 i got the div to be clicked by $('div') and first gave it an action of changing the mouse to cursor to indicate its clickable and then gave it the click function, where our background-image get changed on click 我得到了divclicked通过$('div') ,并第一次给它改变鼠标光标,以表明其点击的动作,然后把它的点击功能,在这里我们的背景图像上得到改变点击

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

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