2013-03-02 39 views
0

我希望用戶可以選擇在我的網站上更改背景圖片,所以我找到了一些允許他們執行此操作的代碼。這使他們能粘貼在一個文本框他們選擇的圖像的URL(輸入):允許用戶在HTML網頁上更改和保存背景圖片

<script type="text/javascript"> 
function changebackground(){ 
    var url = document.getElementById('bgchanger').value; 
    document.getElementsByTagName('body')[0].style.backgroundImage = "url('" + url + "')"; 
} 
</script> 

<input type="text" id="bgchanger" placeholder="Change Background Add URL" /> 
<input type="button" onclick="changebackground();" value="Change!" /> 

的所有作品,但是當用戶離開網站或點擊刷新背景圖像會白回來(默認)

我想知道我們是否可以在下次訪問該網站時保存用戶背景圖片。

我已經做了演示:

DEMOhttp://goo.gl/253IN

用戶名:演示

密碼:demo1的

謝謝喲你提前!

PS我不是專家:對HTML和JAVASCRPIT(但d),所以我將無法理解真正複雜的代碼

+0

店在cookie中的設置。 – 2013-03-02 16:43:52

+0

或localStorage – 2013-03-02 16:44:17

回答

0

的jQuery的,而不是用localStorage的嘗試

var defaultImage = "http://..."; 
    document.getElementsByTagName('body')[0].style.backgroundImage = localStorage.getItem('back') ? "url('"+localStorage.getItem('back')+"')" : "url('"+defaultImage+"')"; 
    function changebackground(){ 
     var url = document.getElementById('bgchanger').value; 
     document.getElementsByTagName('body')[0].style.backgroundImage = "url('" + url + "')"; 
     localStorage.setItem('back',url); 
    } 
+1

謝謝你的幫助:D它的工作原理 – Giovanni 2013-03-02 16:59:08

0

一個好辦法做到這一點是使用localStorage的。我已經寫了一個jQuery插件來處理它更容易。看看例子。 https://github.com/yckart/jquery.storage.js

+0

'您可以選擇包含一個$ .cookie插件 以支持舊瀏覽器(eq IE lt 7)'..所以它不支持所有瀏覽器.. – 2013-03-02 16:52:42

+0

@GioL我認爲使用cookie不再需要:http://caniuse.com/#search=localstorage – yckart 2013-03-02 18:41:30

1

做到這一點..你必須把用戶計算機上的cookie,然後檢查是否設置cookie和檢索它的價值,......

這裏是餅乾 https://github.com/carhartl/jquery-cookie

一個jQuery插件

首先你創造的餅乾

$.cookie('background_image', url , { expires: 7 });// will expire in 7 days 

那麼你檢查是否該cookie設置

if(typeof($.cookie('background_image')) != 'undefined'){ 
    var users_old_back_ground = $.cookie('background_image'); 
    $('body').css ({ "background-image" : "url('" + users_old_back_ground + "')"}); //jquery : selecting the body tag ... then using css() to set the bg 
}else{ 
    // do something else because the user doesnt have the cookie 
} 

,並嘗試提升你以前的代碼,並使用普通的JavaScript

+0

感謝您的幫助:D – Giovanni 2013-03-02 17:03:59

+0

您不止歡迎..嘗試學習jQuery,它非常簡單而強大。 :)祝你好運 – 2013-03-02 17:05:32

+0

@codeiz嘗試學習的JavaScript,這很容易,也許讓你讓jQuery更強大;) – yckart 2013-03-02 17:38:24