当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JQuery插件Style定制化方法的分析与比较

JQuery插件Style定制化方法的分析与比较

2018年10月13日  | 移动技术网IT编程  | 我要评论

最近因为项目的需要,使用了一个jquery插件。把插件下下来后,很快我就发现,很多默认的插件style不符合项目要求,必须要被修改。
在这个过程中,我发现自己先后使用了多种不同的方法实现插件style的定制化。很高兴最后找到了我认为最好的方法,对css的认识也加深了不少,感触颇多。这篇文章就是对这些新的css的认识的一个梳理。
2jquery 插件style 定制化方法
2.1 初始化插件时输入定制化对象
做的比较好的插件会在初始化时允许输入定制化对象。
如果输入定制化对象,插件会使用定制化对象中的值,例如,

代码如下:


var adgallerysetting = {
width: 600, // width of the image, set to false and it will read the css width
height: 400, // height of the image, set to false and it will read the css height
}
var galleries = $('.ad-gallery').adgallery(adgallerysetting);


如果不输入定制化对象,插件会使用它自己的默认值,例如,
var galleries = $('.ad-gallery').adgallery();
2.2 修改插件的css
如果插件没有提供定制化对象或你想要修改的style不在定制化对象定义里,一个比较直观的方法是修改插件的css文件。这不是一种值得提倡的方法,因为这会corrupt插件的本身的源代码,且不利于以后插件版本的更新。
2.3 注册callback函数
大部分插件还在定制化对象里定义callback函数。如果callback函数在插件完成style enhance后调用,你可以写这个callback并注册,在callback里修改dom模型,从而完成插件style的定制化。这种方法比较繁琐,需要你花比较多的时间去理解插件内部的实现。例如,

. 代码如下:


var adgallerysetting = {
// all callbacks has the adgallery objects as 'this' reference
callbacks: {
// this gets fired right before old_image is about to go away, and new_image
// is about to come in
beforeimagevisible: function(new_image, old_image) {
// do something wild!
var thing = "this is it";
//change the plugin enhanced page
$(".ad-gallery .ad-image-wrapper .ad-image").removeattr("style");
$(".ad-gallery .ad-image-wrapper .ad-image").css("width", "100%");
var width = $(".ad-gallery .ad-image-wrapper .ad-image img").attr("width");
$(".ad-gallery .ad-image-wrapper .ad-image img").attr("width", "100%");
$(".ad-gallery .ad-image-wrapper .ad-image .img").attr("width", 100%);
$(".ad-gallery .ad-image-wrapper .ad-image").attr("height", 100%);
}
}
};


2.4 增加一个新的css文件,重载插件的部分style
css是cascading style sheet 的缩写,固名思义,它有一个cascading 标准。当多个css 文件对同一个html element的style定义有冲突时,它会根据以下规则决定apply哪个css style.
1) ! important 标识。
2) 来源。 author (html链入的css文件), reader(web surfer), user agent(browser)
3) 相关性。
具体可以查看参考部分的链接网页。
这种方法,在我看来是除1.1 外最好的方法,下面是些代码示例。

. 代码如下:


#descriptions .ad-image-description {
position: absolute;
}
#descriptions .ad-image-description .ad-description-title {
display: block;
}
.ad-gallery .ad-image-wrapper .ad-image {
width: 100% ! important;
left: 0px ! important;
}


3总结
根据这次的经验,我觉得定制插件style的最好方法输入定制化对象(如果插件支持的话)或css重载。有些插件会以在html element中加入style="...."的方式定义style。在这种情况下,你就会发现,“! important”标识的出现是相当的令人舒心。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网