如何用Javascript更改div位置?

时间:2016-06-11 13:14:10

标签: javascript

所以,这是我到目前为止所得到的:https://jsfiddle.net/625qofbe/1/

我想要的是“约”div的位置,包含Lorem Ipsum文本和什么应该是“X”符号(我不知道如何将图像链接到JSfiddle,对不起)移动,比方说,30像素当用户点击左上角的“关于”按钮时向左。这是我一直试图用的Javascript:

document.getElementById("button").addEventListener("click", AboutOnScreen);

function AboutOnScreen() {
    document.getElementById("about").style.left = 30px;
}

我一直在谷歌搜索和检查Javascript对这样的成功的小实验多年来,但没有任何工作,我无法看到我在这里做错了。

最终目标是让Lorem文本隐藏在屏幕外,当用户点击“关于”时滑入,然后在点击X图标后滑动屏幕。我确信我在理论上知道这是怎么做的,但我在第一步遇到了障碍。

编辑:感谢帮助人员,但奇怪的是,即使我将代码复制/粘贴回Sublime Text,这两种解决方案在JSfiddle中都运行良好。但是,我确实通过删除“addEventListener”行并将“onclick ='AboutOnScreen()'”添加到“关于”按钮的div标记中来完成工作。当我检查页面源(由Arindam建议)时,“addEventListener”行发送了错误通知,所以我完全摆脱了它。奇怪的是,我确信我之前没有成功,所以解决这个令人头疼的问题最终成为以下所有答案的汇合。

2 个答案:

答案 0 :(得分:2)

如@Rikard所述,请执行以下操作:

document.getElementById("button").addEventListener("click", AboutOnScreen);

function AboutOnScreen() {
    document.getElementById("about").style.left = '30px';
}

哪个应该让代码片段正常工作。 至于滑动动画,你可以使用CSS3(假设浏览器支持)快速为你的页面添加动画。

CSS3动画的一个很好的资源是http://www.w3schools.com/css/css3_animations.asp

祝你好运,玩得开心!

答案 1 :(得分:1)

在普通JS中设置元素距离值的内联样式时,它是Number和String或String的组合。因此,值可以是:public function get_section_news($id_section = 0, $length = 0, $id_sub_section = 0, $id_news_lessthan = 0) { $arr = [] or array(); // if (intval($id_section) > 0 and intval($length) > 0) { // $where = [] or array(); $where['sections.activity'] = 1; $where['news.deleted'] = 0; $where['news.id_section'] = $id_section; $query = $this->db; $query ->from("news") ->join("sections", "news.id_section = sections.id_section", "inner") ->order_by("news.id_news", "desc") ->limit($length); // if (intval($id_sub_section) > 0) { $where['news.id_section_sub'] = $id_sub_section; } if ($id_news_lessthan > 0) { $where['news.id_news <'] = $id_news_lessthan; } // $get = $query->where($where)->get(); $num = $get->num_rows(); if ($num > 0) { // foreach ($get->result() as $key => $value) { $arr['row'][] = $value; } } $arr['is_there_more'] = ($length > $num and $num > 0) ? true : false; } return $arr; } '430px'

430+'px'

你说向左移动30px,这被解释(至少对我来说),因为当前位置距离元素30px。所以它是document.getElementById("button").addEventListener("click", AboutOnScreen); function AboutOnScreen() { document.getElementById("about").style.left = 430 + 'px'; } 所以如果向左移动30px,则值应为left: 400px

FIDDLE