你好,
我有這樣的html:
<div id="inputarea" style="color:black;font-size:15px;">
我想將樣式資料存盤到 cookie 中,所以我這樣做了:
setCookie('savedstyle',inputarea.style);
因此,在我的下一個會話中,inputarea 應該從該 cookie 加載資料并將其設定為 inputarea 的樣式,如下所示:
if(getCookie('savedstyle')) {
inputarea.style = getCookie('savedstyle');
}
沒有任何反應,因為存盤在 cookie 中的值看起來像這樣:[object CSS properties]。這是為什么?如何正確存盤值?
謝謝你。
uj5u.com熱心網友回復:
.stylein JS 只存盤 CSS 屬性的設定器。它對閱讀資訊沒有用處。
如果您只想存盤行內樣式,請使用:
setCookie('savedstyle', inputarea.getAttribute('style'))
并檢索
inputarea.setAttribute('style', getCookie('savedstyle'))
uj5u.com熱心網友回復:
試試這些。這些是我在需要時用于專案的一些樣板函式。
readCookie = (cname) =>
{
let name = cname '=';
let decodedCookie = decodeURIComponent(window.document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i )
{
let c = ca[i];
while (c.charAt(0) == ' ')
{
c = c.substring(1);
}
if (c.indexOf(name) == 0)
{
return c.substring(name.length, c.length);
}
}
return '';
}
createCookie=(cname, cvalue)=>
{
let d = new Date();
d.setTime(d.getTime() (10*24*60*60*1000));
let expires = 'expires=' d.toUTCString();
window.document.cookie = cname '=' cvalue ';' expires ';path=/';
}
deleteCookie = (name) =>
{
if(readCookie(name))
{
window.document.cookie = name '=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT';
}
}
readCookie 函式通過名稱讀取 cookie。createCookie 你給它一個名字和一個值,而 deleteCookie 按名字洗掉一個cookie。非常不言自明:D。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420521.html
標籤:
