4

是否有确定最接近目标元素的元素(任何元素)是否具有 z-index 的正确方法?

例如,我将一个 div 附加到一个 DOM 层,我想知道该 div 附近是否有一个带有 z-index 的元素,以便我可以相应地定位该 div,这样它就不会因为我没有而在层下丢失'不知道它会在何时何地被附加。

谢谢!

编辑:

我有一个提示插件,可以动态地将提示附加到页面,然后将它们保存在服务器上。我会发布代码,但恐怕它与我的问题没有太大关系。

4

3 回答 3

2

我会创建一个类似下面的函数。它遍历每个元素的父元素并检查它是否具有 z-index

    function getElement($target){
       var $parents = $target.parents();
       for(var i=0;i<$parents.length;i++){
          if($parents[i].css('z-index').length>0){
              return $parents[i];
          }
       }
       return false;

    }
于 2013-10-28T04:46:36.927 回答
0

My is a similar solution as the one from Sethunath.

/**
 * Helper to retrieve the z-index which is required to bring up the dragged element in front.
 * @returns {undefined}
 */
getZIndex: function () {
    if (this.z_index === undefined) {

        var recrusive_z_index_search = function(element) {

            // Break on body.
            if (element[0] === $('body')[0]) {
                return 2;
            }

            // Get parent element
            var parent = $(element).parent();

            // Check if parent has z-index
            var z_index = parent.css('z-index');
            if (z_index.length > 0 && !(/\D/).test(z_index)) {

                // Return found z-index.
                return z_index;
            }

            // Z-index not found, try again on next parent.
            return recrusive_z_index_search(parent);
        };

        this.z_index = recrusive_z_index_search($(this.element));

    }
    return this.z_index;
},

This solution was added within an object class. this.element is the starting point from where it searchs. It stops when we found an element with z-index not really a one with a numeric value, because z-index can also be set to "auto". If we reached the body we break the chain and set it to 2 by default as a fallback.

Hope this helps others.

于 2014-07-07T08:51:00.577 回答
-1

You can use Firefox firebug https://getfirebug.com/ or Chrome Developer Tools (built in Chrome) to inspect the element you'd like to find the z-index of.

Appending the element near another div isn't related to the z-index property. The z-index will bring the highest number element in front when objects overlap. Otherwise, it is not the property you are looking for. Especially if you didn't define any z-index properties for other elements.

CSS specificity is what you might be looking for here

于 2013-10-28T04:49:50.610 回答