javascript - 获取 Javascript div 在出现时滑出

标签 javascript html css

这里有一些基本的 JS,我想滑出而不是仅仅出现(看起来有点问题)

我尝试了一些方法,但就是无法管理,有什么想法吗?这是 Jsfiddle 后面的代码:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<style>
body{margin:0;}
#foo{min-width:400px; height:100%; background-color:#9C0; display:none; position:absolute; right:0px; top:0px;}


</style>
<body>
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo" >



</div>


<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>
</body>
</html>

JsFiddle

最佳答案

我已经使用 VanillaJS 更新了你的 fiddle as you can see here它工作得很好

document.getElementById('bar').onclick = (function()
{
    var that, interval, step = 20,
    id = document.getElementById('foo'),
    handler = function()
    {
        that = that || this;
        that.onclick = null;
        id = document.getElementById('foo');
        interval =setInterval (function()
        {
            id.style.right = (parseInt(id.style.right, 10) + step)+ 'px';
            if (id.style.right === '0px' || id.style.right === '-400px')
            {
                that.onclick = handler;
                clearInterval(interval);
                if (id.style.right === '-400px')
                {
                    id.style.display = 'none';
                }
                step *= -1;
            }
            else
            {
                id.style.display = 'block';
            }
        },100);
    };
    return handler;
}());

代码解释:

  • 在 JS 中附加点击处理程序,因为我们必须动态地取消绑定(bind)/绑定(bind)它
  • 我没有直接分配处理程序,而是使用闭包(用于间隔和 DOM 引用)
  • handler 是实际的事件处理程序,它将其上下文(单击的元素)分配给 that,因此我们可以在间隔回调中引用它并取消绑定(bind) 处理程序。
  • 间隔按 step 像素更改元素的位置(将此值设置为您喜欢的任何值)。
  • 如果 div 位于位置 0 或 -400,则取消间隔(这就是我们需要闭包的原因,以将间隔 ID 保持在范围内,但不将其公开到全局),然后重新绑定(bind)点击处理程序,step *= -1,反转动画
  • 设置显示属性

此间隔序列设置为每 100 毫秒发生一次,这有点不稳定,将 set 的值降低到 10,并将间隔设置为 50 应该会使事情变得平滑出

关于javascript - 获取 Javascript div 在出现时滑出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17467406/

相关文章:

jquery - 根据 th 的类隐藏 td 元素

css - 渐变文字颜色

HTML CSS 如何去掉滚动条让网站全屏?

javascript - HTML 不会从 <head> 加载文件

javascript - 如何在 Highcharts 中添加自定义图标作为标记

javascript - 使用 google street view image api v3 如何使用 javascript 保存街景图像

c# - 使用c#在mvc4中使用viewbag数据的下拉列表

jquery - ng-click 不适用于动态生成的 HTML

JavaScript:为什么 map.has 比 set.has 和 array.indexOf 快这么多?

javascript - NodeJS Passport 本地身份验证不起作用