0

我使用了功能切换,如果我刷新页面,它会记住切换的位置。我尝试使用会话,但找不到更新会话的方法(当用户希望看到更多或更少时)。

这是我的代码:

<script language="javascript"> 
    function toggle(showHideDiv, switchImgTag) {    
            var ele = document.getElementById(showHideDiv);
        var imageEle = document.getElementById(switchImgTag);
        if(ele.style.display == "block") {
            ele.style.display = "none";
            imageEle.innerHTML = '<img src="more.png"">';
        }else {
            ele.style.display = "block";
            imageEle.innerHTML = '<img src="less.png">';        
        }
    }

</script>   

<?php 
if(empty($_SESSION["toggle"])){
 $_SESSION["toggle"] = 'show'; 
}?>

<a id="imageDivLink" href="javascript:toggle('contentDivImg', 'imageDivLink');"><img src="lesss.png"></a>Title

<?php if($_SESSION["toggle"] == 'show'){ ?>
  <div id="contentDivImg" style="display: block;">
<?php 
   $_SESSION["toggle"] = 'hidden'; 
 } 
 if($_SESSION["toggle"] == 'hidden'){ ?>
   <div id="contentDivImg" style="display: none">
<?php $_SESSION["toggle"] = 'show'; 
 } ?>
Try Show & hide
</div>
4

1 回答 1

2

我第二个 @Akam 和 @ChaseMoskal 建议您为此使用 JavaScript。

它应该像这样简单

<html>
<head>
<script type="text/javascript"> 
    function toggle(showHideDiv, switchImgTag) {    
        var ele = document.getElementById(showHideDiv);
        var imageEle = document.getElementById(switchImgTag);
        if(ele.style.display == "block") {
            // Also set the toggle cookie on toggle
            document.cookie = 'toggle=hide'
            ele.style.display = "none";
            imageEle.innerHTML = '<img src="more.png"">';
        }else {
            // Also set the toggle cookie on toggle
            document.cookie = 'toggle=show'
            ele.style.display = "block";
            imageEle.innerHTML = '<img src="less.png">';        
        }
    }
</script>   
</head>
<body>

<a id="imageDivLink" href="javascript:toggle('contentDivImg', 'imageDivLink');"><img src="lesss.png"></a>Title


<div id="contentDivImg" style="display:block">Try Show & hide</div>


<script type="text/javascript">
    // Run at the end of the body so that the dom is ready for us
    // Dont beleave me? reade this: https://groups.google.com/forum/#!topic/closure-library-discuss/G-7Ltdavy0E
    (function(){
        // Get the cookie we want to check using a fancy-pants regex
        var cookie = document.cookie.replace(/(?:(?:^|.*;\s*)toggle\s*\=\s*([^;]*).*$)|^.*$/, "$1");
        if (cookie === 'hide')
            // If the cookie says hide, just use the toggle function
            // The user wont see the change because were still running way before readystate complete
            toggle('contentDivImg', 'imageDivLink');
    }())
</script>
</body>
</html>

这使用 document.cookie 将切换 cookie 设置为显示或隐藏。如果切换 cookie 是隐藏的,则在页面完成加载之前调用切换函数。


请注意,虽然当文件通过 http(s) 从远程服务器(或本地主机)提供时,这将起作用,但如果使用 file: 协议检索文件,它将不起作用,因为 cookie 与域相关联。

如果您想了解有关在 JavaScript 中使用 cookie 的更多信息,或者只是想复制和过去一些有用的功能(甚至是一个小框架),请查看MDN 文章

于 2013-08-20T09:55:55.830 回答