[英]Move only some CSS styles from one element to another
我創建了一個jQuery插件,它接受一個HTML表,使其可以排序,並修復頁眉和頁腳。 有關示例,請參閱http://jsfiddle.net/aXDzz/ (單擊“創建”以創建表)。
效果很好,但最近需要在桌子周圍添加一些填充或邊距。 這引起了一些問題。
我的插件基本上用一個<div>
替換原來的<table>
,其中包含一個<table>
作為標題,一個<div>
,其中實習生包含一個<table>
用於正文,一個<table>
用於頁腳。 我的意圖是讓用戶將CSS應用於原始表,並且在使用我的插件時,CSS將適當地傳輸。 但是,如上所述,我在表格周圍包裹一個<div>
,以便現在邊距或填充應該應用於<div>
而不是<table>
。
所以,看起來我需要將適用於<table>
外部的任何CSS移動到<div>
例如margin,但是然后留下任何適用於<table>
內部的CSS,例如僅行顏色。
我該怎么做? 或者是否有一個更好的方法我應該實現這個? 謝謝
PS。 請隨意批評我的插件,因為這是我的第一次嘗試。
我檢查了你的代碼,我試圖在你的桌子上申請保證金:
.myTable {
width:600px;
matgin-left: 50px;
}
然后我看到了問題所在。 但后來我看了代碼,你指定固定寬度
<div style="width: 618px; overflow-y: auto; max-height: 300px;"><table id="myTable" class="myTable">
而這似乎導致了問題。
看一眼:
width: 618px;
如果我正確理解了這個問題,那就不算好了。 也許您可以嘗試在插件中找到計算寬度的位置,然后將邊距包含在計算寬度的計算中。 到目前為止我還沒有找到。 這個插件很長..
當我放,例如665px,它看起來有點好..
也許這就是解決方案。
我試圖根據您的需要修改此插件:
(function($){
$.fn.copyStyle = function(jqCopyTo,styleStartsWith,overideStyle){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
for(var m = 0; m < styleStartsWith.length; m++){
if(prop.lastIndexOf(styleStartsWith[m], 0) === 0) {
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
overideStyle==true ? $(this).css(prop,0):null;
}
}
};
};
if(style = dom.currentStyle){
for(var prop in style){
for(var m = 0; m < styleStartsWith.length; m++){
if(prop.lastIndexOf(styleStartsWith[m], 0) === 0) {
returns[prop] = style[prop];
overideStyle==true ? $(this).css(prop,0):null;
}
}
};
};
//copy
$(jqCopyTo).css(returns);
return this;
}
})(jQuery);
在這樣的結構上:
#inner {
margin:20px;
padding:20px;
background-color:#F00;
}
#wrapper {
background-color:#f80;
}
HTML:
<div id="wrapper">
<div id="inner">
Table Content
</div>
</div>
你可以像這樣使用這個插件:
$("#inner").copyStyle("#wrapper",["margin","padding"],true);
結果是內部邊距和填充被覆蓋,並且樣式被添加到wrapper-div。 您可以使用最后一個布爾指示符處理覆蓋行為。
這是jsFiddle的完整示例。 我無法保證它適用於所有瀏覽器(僅測試過Firefox和ie9)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.