我写了一些jQuery,点击后会将按钮变形为容器。
我现在想要使用相同的脚本,但在不同的按钮上。我不确定最好的方法。是复制并粘贴整个morphObject
,然后更改需要更改新按钮的位,然后同时运行对象的初始化函数?
这是小提琴: https://jsfiddle.net/2a3rp590/
这是jQuery:
$(document).ready(function() {
var morphObject = {
button: $('button.morphButton'),
container: $('div.morphContainer'),
overlay: $('div.overlay'),
content: $('h1.content, p.content'),
endPosition: {
top: 100,
left: '50%',
width: 600,
height: 400,
marginLeft: -300
},
init: function() {
var mO = morphObject,
button = mO.button;
button.on('click', function() {
button.fadeOut(200);
setTimeout(mO.containerMove, 200);
});
},
containerMove: function() {
var mO = morphObject,
content = mO.content,
overlay = mO.overlay,
container = mO.container,
span = $('span.close');
overlay.fadeIn();
container.animate(mO.endPosition, 400, function() {
content.fadeIn();
span.fadeIn();
mO.close();
});
},
close: function() {
var mO = morphObject,
container = mO.container,
overlay = mO.overlay,
content = mO.content;
if ( container.find('span.close').length ) return;
$('<span class="close">X</span>').appendTo(container);
var span = $('span.close');
overlay.add(span).on('click', function() {
content.fadeOut();
span.fadeOut();
overlay.fadeOut();
setTimeout(mO.animateBack, 200);
});
},
animateBack: function() {
var mO = morphObject,
container = mO.container;
button = mO.button;
container.animate(mO.startPosition, 400, function() {
button.fadeIn(300);
});
}
}
var container = morphObject.container;
morphObject.startPosition = {
top: container.css('top'),
left: container.css('left'),
width: container.css('width'),
height: container.css('height'),
marginLeft: container.css('margin-left')
};
morphObject.init();
});
你可以在小提琴中看到,我添加了一个新的按钮,容器和内容。如何使用多个按钮使我的代码工作?
感谢。
答案 0 :(得分:0)
正如我在评论中所说,你可以做到以下几点。请记住,这是未经测试的版本。
init: function(params) {
//object reference
var self = this;
//reassign the button object if it was passed
//else use the default from the object
self.button = typeof params !== "undefined" && params.button || self.button;
self.button.on('click', function() {
$(this).fadeOut(200);
setTimeout(self.containerMove, 200);
});
}
//I am using an object as you my want to
//pass in more options later, just in case
//such as
/*
morphObject.init({
button: $('button.morphButton2'),
container: $('.another-container')
});
*/
morphObject.init({
button: $('button.morphButton2')
});
或者你可以在所有按钮上都有一个公共类,它会触发init方法内的点击。够容易吗?
var morphObject = {
button: $('button.morphButton') //let's say 'morphButton' is the common class
.....
.....
init: function(params) {
//object reference
var self = this;
self.button.on('click', function() {
$(this).fadeOut(200);
setTimeout(self.containerMove, 200);
});
}
.....
.....
.....
}