jQuery

2010-03-11 9 views
8

के साथ सापेक्ष तत्व ढूंढें क्या तत्व को खोजने के लिए कोई सरल और साफ jquery-way है जिस पर तत्व की इसकी सापेक्ष स्थिति है? दूसरे शब्दों में: पहले माता-पिता को ढूंढना जिनके पास सीएसएस विशेषता position: relative है, या बॉडी-एलिमेंट (यदि कोई मूल तत्व position: relative नहीं है)।jQuery

मैं नहीं जानता- सीएसएस-वर्ग या माता-पिता का क्या पता है।

उत्तर

10

तत्व के साथ शुरू $elem

var $closestRelativeParent = $elem.parents().filter(function() { 
    // reduce to only relative position or "body" elements 
    var $this = $(this); 
    return $this.is('body') || $this.css('position') == 'relative'; 
}).slice(0,1); // grab only the "first" 
2

में लोड मुझे लगता है कि आप यह पहली रिश्तेदार माता पिता है से बच्चे की स्थिति की गणना करने के लिए इस जानना चाहता हूँ चाहते हैं। मैं सुझाव दूंगा कि बेहतर दृष्टिकोण केवल jQuery की .offsetParent() गणना का उपयोग करना होगा, जो fixed और absolute की स्थिति के माता-पिता की भी तलाश करेगा, क्योंकि इससे बच्चे की स्थिति पर भी असर पड़ेगा।

जिसके अनुसार, यहां .offsetParent() का उपयोग कर इसे रिश्तेदार की स्थिति (see JSFiddle) है की गणना करने के बारे में आप कैसे जा सकते हैं की एक त्वरित नकली है:

// Given a target, find it's first offset parent, and work out the targets position 
// relative to the parent, by deducting their respective .offset() values 
var $target = $("#bar"), 
    $offsetParent = $target.offsetParent(), 
    oTarget = $target.offset(), 
    oParent = $offsetParent.offset(), 
    posTop = oTarget.top - oParent.top, 
    posLeft = oTarget.left - oParent.left; 

// Validate this works by cloning #bar and positioning the clone directly on top 
// Result should be a blue "bar" rather than a "red" one. 
$target.clone().appendTo($offsetParent).attr("id", "confirm").css({ 
    top: posTop, 
    left: posLeft 
}); 
+1

बिल्कुल पोजीशनिंग बच्चे तत्वों के लिए सबसे अच्छा समाधान! –