我正在编写一个简单的JS功能。 当我点击红色div时,我希望黄色和绿色div在它下面进行简单的滑动,黄色和绿色都不应该可见,因为它们将隐藏在红色背后。 类似地,当我点击红色div时,绿色和黄色div应该以相同的滑动功能打开。
我正在尝试实现与以下网址类似的幻灯片移动。
var whatever = document.getElementById("whatever");
Array.prototype.push.apply((whateversChildren = []), whatever.children);
whateversChildren.splice(0,1);
whatever.children[0].onclick = (function() {
if (whatever.children.length > 1) {
for (var i = 0; i < whateversChildren.length; i++) {
whatever.removeChild(whateversChildren[i]);
whatever.firstElementChild.appendChild(whateversChildren[i]);
}
} else {
for (var i = 0; i < whateversChildren.length; i++) {
whatever.firstElementChild.removeChild(whateversChildren[i]);
whatever.appendChild(whateversChildren[i]);
}
}
});
答案 0 :(得分:1)
正如您已标记此JavaScript我正在遵循标记说明并且:
除非还包含框架/库的标记,否则需要纯JavaScript答案。
这可能是一个开始。依靠CSS和JavaScript中的转换来计算一些左侧位置。
在“all”上设置转换,这意味着更改的任何样式属性将由给定的时间更改。在代码示例中,它设置为0.75秒。
<强> Fiddle demo 强>
CSS:
#whatever div {
position : relative; /* Added. For movement and z-index */
transition : all .75s; /* Added. For animation/slide */
}
#c1 {
z-index : 10; /* Added. To keep it atop. */
cursor : pointer; /* Added. For nicety. */
}
.show {
opacity : 1;
}
.hide {
opacity : 0.3;
z-index : 1;
}
JavaScript的:
function Slider(id) {
var box = document.getElementById(id);
// CSS class names
this.css = {
show : 'show',
hide : 'hide'
};
// Array holding left position for each element.
this.pos = [];
// Get all the children
this.ch = box.getElementsByTagName('DIV');
this.ch[0].onclick = this.click.bind(this);
// Get initial positions.
this.fillPos();
// Make sure to add class show.
this.show();
}
// Find left position of an element.
Slider.prototype.left = function(e) {
var x = e.offsetLeft;
while (e = e.offsetParent) {
x += e.offsetLeft;
}
return x;
};
// Get left position for all elements.
Slider.prototype.fillPos = function() {
var i;
this.pos = [];
for (i = 0; i < this.ch.length; ++i) {
this.pos.push(
this.left(this.ch[i])
);
}
};
// Show
Slider.prototype.show = function() {
var i;
for (i = 1; i < this.ch.length; ++i) {
this.ch[i].className = this.css.show;
this.ch[i].style.left = '0';
}
};
// Hide
Slider.prototype.hide = function() {
var i;
for (i = 1; i < this.ch.length; ++i) {
this.ch[i].className = this.css.hide;
// Set left equal to left minus left position of first (red) element.
this.ch[i].style.left = -(this.pos[i] - this.pos[0]) + 'px';
}
};
// Event handler.
Slider.prototype.click = function(e) {
if (this.ch[1].className === 'hide')
this.show();
else
this.hide();
};
// Create new slider
var sly = new Slider("whatever");