quiz icon indicating copy to clipboard operation
quiz copied to clipboard

DOM基础测试37

Open zhangxinxu opened this issue 5 years ago • 32 comments

本期题目如下,关于

元素。

大家提交回答的时候,注意缩进距离,起始位置从左边缘开始;另外,github自带代码高亮,所以请使用下面示意的格式(缩进和代码高亮1积分)。

```js
// 你的JS代码写在这里
 ```

**心怀瑞雪,自己作答,不要参考别人回答**

其他 因为本周六是中秋节,很多人会出去放松,因此本期小测答疑挪到下周和下周下册一起。直播地址:https://live.bilibili.com/21193211

每位答题者会有至少2积分参与分,本次小测满分10积分。

首位答题者将会获得100%被翻牌的技能。

zhangxinxu avatar Sep 11 '19 11:09 zhangxinxu

1.
const dialog = document.createElement('dialog')
document.body.append(dialog)
2.
//dialog.open = 'aa'
3.
const btn = document.createElement('button')
btn.innerText='button'
dialog.appendChild(btn)

btn.addEventListener('click', ()=>{
  dialog.close()
})
4.
dialog.showModal()
5.
其他dialog使用show方法,最后一个使用showModal

GitHdu avatar Sep 11 '19 11:09 GitHdu

1

var dialog = document.createElement('dialog');
document.body.append(dialog);

2

dialog.open = true;
// 或者
dialog.setAttribute('open','open');
// 或者
dialog.show();

3

var button = document.createElement('button');
button.textContent = 'close';
dialog.appendChild(button);
button.addEventListener('click',function(){
  this.parentNode.close();
})

4

dialog.showModal();

5 扩展一个showTop方法 demo

HTMLDialogElement.prototype.showTop = function(){
  if(window.topDialog) {
    window.topDialog.style.zIndex = 'auto';
  }
  window.topDialog = this;
  this.close(); // showModal必须先关闭再打开层级才生效
  this.style.zIndex = 99;
  this.showModal();
}

XboxYan avatar Sep 11 '19 12:09 XboxYan

第1题

const diag = document.createElement('dialog')
document.body.appendChild(diag)

第2题

diag.open = 'xxxx'

第3题

const btn = document.createElement('button')
btn.innerText='关闭'
btn.addEventListener('click',function(){
    this.parentNode.open = false
    //发现正确的方式应该是调用close(),这样做遮罩会去不掉
})
diag.appendChild(btn)

第4题

diag.showModal()

第5题

通过 showModal() 调用的 dialog 元素总会出现再最上层,z-index 此时没有作用,但是通过show() 会有层级的问题

//找到所有 dialog 元素
const diags = document.querySelectorAll('dialog')
//找出z-index 最大值
const max = Math.max(...[...diags].map(e => e.style.zIndex))
//需要 show diag 元素 z-index 加 1
diag.style.zIndex = `${max + 1}`
diag.show()

tao1874 avatar Sep 11 '19 13:09 tao1874

第一题

var Dialog=document.createElement('dialog');
document.body.appendChild(Dialog);

第二题

Dialog.open='true';

第三题

var Button=document.createElement('button');
Button.innerText="关闭";
Button.type="button";
Dialog.append(Button);
Button.addEventListener('click',function(){
    Dialog.close();
});

第四题

Dialog.showModal();

第五题

dialog{
  z-index:99;
}
dialog:focus-within{
  z-index: 100;
}

ziven27 avatar Sep 11 '19 13:09 ziven27


const dialogElm = document.createElement('DIALOG')
document.body.appendChild(dialogElm)
dialogElm.appendChild(btnElm);

// 第二题
// dialogElm.setAttribute('open', '任意字符串')   

// 第三题
const btnElm = document.createElement('BUTTON')
btnElm.innerText = '关闭'
btnElm.addEventListener('click', e => {
  // dialogElm.removeAttribute('open')
  dialogElm.close()
})
第四题
// dialogElm.showModal() //自带遮罩

第五题 遍历所有dialog再把最大的zindex加1

function showDialog(dialog) {
  // 使用 showModal 时后出现的就在最高的层级
  // document.querySelectorAll('dialog')[index].showModal()
  dialog.show()
  const dialogList = [...document.querySelectorAll('dialog[open]')].map(elm => elm.style.zIndex || 0)
  if (!dialogList.length) {
    return
  }
  const maxZindex = Math.max.apply(null, dialogList)
  dialog.style.zIndex = maxZindex + 1
}

livetune avatar Sep 11 '19 13:09 livetune

第一题

let newDialog = document.createElement('dialog');
document.body.appendChild(newDialog);

第二题

newDialog.setAttribute('open', '开启');

第三题

let btn = document.createElement('button');
btn.innerText = '关闭dialog'
btn.addEventListener('click', function () {
    newDialog.removeAttribute('open');
});
newDialog.appendChild(btn);

第四题

newDialog.showModal();

第五题

function setMax() {
    let dialogs = document.querySelectorAll('dialog');
    let largestIndex = 1;
    Array.from(dialogs).forEach(dom => {
        if (Number(dom.style.zIndex) > largestIndex) {
            largestIndex = Number(dom.style.zIndex)
        };
    });
    dialogs[dialogs.length - 1].style.zIndex = largestIndex + 1

}
setMax();

rayj1993 avatar Sep 11 '19 15:09 rayj1993

//1
var dialog=document.createElement('dialog')
document.body.appendChild(dialog)
//2
dialog.open='open'
//3
var button=document.createElement('button')
button.innerText='x'
button.addEventListener('click',()=>dialog.close())
dialog.appendChild(button)
//4
dialog.close()
dialog.showModal()
//5
nodelist=Array.from(document.querySelectorAll("dialog"))
var maxIndex=Math.max(...nodelist.map(v=>getComputedStyle(v).zIndex).filter(v=>v!=='auto'))
dialog.style.zIndex=maxIndex+1

Seasonley avatar Sep 11 '19 15:09 Seasonley

第 1 题:

const dialog = document.createElement('dialog');
document.body.appendChild(dialog);

第 2 题:

// 方法1:
dialog.open = true;  // 或其他为“真值”的基本类型,如 1,"abc" 等

// 方法2:
dialog.show();

// 方法3:
dialog.showModal();

第 3 题:

const btn = document.createElement('button');

btn.innerText = 'close';
btn.addEventListener('click', () => {
  // 方法1:
  dialog.open = false;  // 或其他“非真”的基本类型,如 0、null 等

  // 方法2:
  dialog.close();
});
dialog.appendChild(btn);

第 4 题:

// 用 showModal 方法即可让打开的 dialog 自带遮罩,在 CSS 里可通过 ::backdrop 设置遮罩层样式
dialog.showModal();

第 5 题:

思路:如果是 showModal() 方法打开的 dialog,则其覆盖层级默认是置顶的;而通过 show() 方法或 open 属性打开的 dialog,其覆盖层级遵循“后来居上”原则,所以需要手动调整其 z-index 值来使其覆盖层级置顶。

(function(dialogElm) {
  if (!dialogElm) return;

  const proto = dialogElm.prototype;
  const oldShow = proto.show;
  const dialogBaseLevel = 100;  // 对话框弹层的基准层级(根据项目zIndex规范合理设置)
  const getMaxZIndex = () => {
    const dialogs = document.querySelectorAll('dialog[open]');
    const maxZIndex = Math.max.apply(null, [...dialogs].map(it =>
      it.style.zIndex || Number(window.getComputedStyle(it).zIndex) || dialogBaseLevel
    ));

    return maxZIndex;
  };
  const setMaxZIndex = el => el.style.zIndex = getMaxZIndex() + 1;

  // 重写 show 方法
  proto.show = function() {
    setMaxZIndex(this);
    oldShow.call(this);
  };

  // "劫持" open 属性
  Object.defineProperty(proto, 'open', {
    set: function(value) {
      const isOpen = Boolean(isNaN(value) ? value : Number(value));
      this[isOpen ? 'show' : 'close']();
    }
  });
})(window.HTMLDialogElement);

测试 Demo

wingmeng avatar Sep 11 '19 15:09 wingmeng

var dialog = document.createElement('dialog')
document.body.appendChild(dialog)
dialog.setAttribute('open', '')
var button = document.createElement('button')
dialog.appendChild(button)
button.onclick = function(){
    this.parentNode.close()
}
dialog.showModal()

fzpijl avatar Sep 11 '19 16:09 fzpijl

    let oDialog = document.createElement("dialog");

    document.body.appendChild(oDialog);

    // oDialog.open = true;

    let oBtn = document.createElement("button");
    oBtn.innerText = "关闭";
    oBtn.addEventListener("click", function(){
        oDialog.close();
    });
    oDialog.appendChild(oBtn);

    // oDialog.show(); //这个不带遮罩
    oDialog.showModal(); //这个带遮罩

    function setMaxZIndex(){
        let aDialog = document.querySelectorAll("dialog");
        let maxZIndex = 0;
        //实现思路,我是想先拿到最大的那个zIndex,然后在把最后个赋值个最大值+1
        [...aDialog].forEach(item => {
            let zIndex = getComputedStyle(item).zIndex;
            if(zIndex > maxZIndex){
                maxZIndex = zIndex;
            }
        });
        aDialog[aDialog.length-1].style.zIndex = maxZIndex + 1;
    }
    setMaxZIndex();

guqianfeng avatar Sep 12 '19 01:09 guqianfeng

let _dialog = document.createElement('dialog')
document.body.appendChild(_dialog)
_dialog.setAttribute('open', 'open')
let _button = document.createElement('button')
_button.innerHTML = 'cancel'
_dialog.appendChild(_button)

_button.addEventListener('click', () => {
  _dialog.close()
})
_dialog.showModal()
// 只要最后一个dialog使用showModal显示时,z-index会失效,即其zIndex层级为最大显示。
lastDialog.showModal()

asyncguo avatar Sep 12 '19 04:09 asyncguo

// 1
var dialog = document.createElement('dialog');
document.body.appendChild(dialog);

// 2
dialog.setAttribute('open', 'true');

// 3
var button = document.createElement('button');
button.textContent = 'close';
dialog.appendChild(button);
button.addEventListener('click', function() {
  dialog.close();
});

// 4
dialog.showModal();

// 5
var initZIndex = 19;
document.querySelectorAll('dialog').forEach(function(el) {
  // 设置层级为最高, 遍历已经为显示状态的 dialog 元素, 获取其最大的 z-index 值
  el._setMaxZIndex = function() {
    var allDialog = Array.from(document.querySelectorAll('dialog[open]'));
    var maxIndex = allDialog.length
      ? Math.max.apply(
          null,
          allDialog.map(function(dialog) {
            var zIndex = window.getComputedStyle(dialog).zIndex;
            return zIndex === 'auto' ? initZIndex : zIndex;
          })
        )
      : initZIndex;
    this.style.zIndex = maxIndex + 1;
  };
  var observer = new MutationObserver(function(mutationList) {
    mutationList.forEach(function(mutation) {
      var target = mutation.target;
      if (!target || !target._setMaxZIndex) {
        return;
      }

      switch (mutation.type) {
        case 'attributes':
          // 当 dialog 的 open 属性为 true 时对其设置 z-index
          if (target.open) {
            el._setMaxZIndex();
          }
          break;
        default:
          break;
      }
    });
  });

  observer.observe(el, {
    attributes: true,
    attributeFilter: ['open']
  });
});

Despair-lj avatar Sep 12 '19 06:09 Despair-lj

// 1
const dialog = document.createElement('dialog')
document.body.append(dialog)

// 2
dialog.open = 'open'

// 3
const btn = document.createElement('button')
btn.innerText = 'Close'
dialog.append(btn)
btn.onclick = function () {
  dialog.close()
}

// 4
dialog.showModal()

// 5 没有头绪

JaimeCheng avatar Sep 12 '19 06:09 JaimeCheng

  • 第一题
 let dialog = document.createElement("dialog");
 document.body.appendChild(dialog);
  • 第二题
dialog.open = "test";
  • 第三题
let button = document.createElement("button");
button.innerText = "close";
button.onclick = () => {
    dialog.close();
};
dialog.appendChild(button);
  • 第四题
 //增加遮盖前删除open属性
 dialog.removeAttribute('open');
 dialog.showModal();
  • 第五题
//之前的dialog使用show
beforeDialog.show();
//最后一个dialog使用showModal,级别高
lastDialog.showModal();

lifelikejuly avatar Sep 12 '19 08:09 lifelikejuly

第一题

var dialog = document.createElement('dialog');
document.body.append(dialog);

第二题

dialog.open = true;

第三题

var btn = document.createElement('button')
btn.innerText='关闭'
btn.addEventListener('click', ()=>{
    this.closest('dialog').close()
})
dialog.appendChild(btn)

第四题

dialog.showModal();

第五题

var observer = new MutationObserver(function (mutationsList) {
    mutationsList.forEach(function (mutation) {
        var target = mutation.target;
        if(target instanceof HTMLDialogElement&&target.open){
            var dialogs = [...document.querySelectorAll('dialog[open]')].filter(dialog=>dialog!==target);
            var maxZIndex = Math.max.apply(null, [...dialogs].map(item =>+item.zIndex || 0));
            if(isNaN(target.zIndex)||target.zIndex<=maxZIndex){
                target.zIndex = maxZIndex + 1;
            }
        }
        
    });
});
observer.observe(document, {
    attributes: true,
    subtree: true,
    attributeFilter: ['open']    
});

liyongleihf2006 avatar Sep 13 '19 04:09 liyongleihf2006

//第一题
var dialog = document.createElement('dialog');
document.body.appendChild(dialog);
//第二题
dialog.setAttribute('open','dialog');
//第三题
var btn = document.createElement('button');
btn.textContent = "btn";
dialog.appendChild(btn);
btn.addEventListener('click',function () {
    dialog.close();
},false);
//第四题 如果使用了showModal就不能有open属性
dialog.showModal();

//第五题

通过测试和查看文档规范,最后一个打开的dialog一定会上面,是否有必要手动设置z-index。 测试地址 image HTMLDialogElement

silverWolf818 avatar Sep 13 '19 05:09 silverWolf818

1.
let dialog = document.createElement('dialog')
    document.body.appendChild(dialog)
2.
dialog.setAttribute('open', true)
3.
let button = document.createElement('button')
button.innerText = "close dialog"
button.onclick = function() {
    dialog.removeAttribute('open')
 }
dialog.appendChild(button)
4.
dialog.showModal()

5 . 不清楚

hangfengnice avatar Sep 13 '19 10:09 hangfengnice

// 第一题
let dialog = document.createElement("dialog")
document.body.appendChild(dialog)
// 第二题
dialog.setAttribute("open","open")
// 第三题
let btn = document.createElement("button")
dialog.appendChild(btn)
btn.addEventListener("click",function(){
 dialog.close()
})
// 第四题
dialog.showModal()
// 第五题
获取所有显示的dialog的z-index值,最后出现的dialog设为前面所有z-index值之和

sghweb avatar Sep 13 '19 14:09 sghweb

var dialogEle = document.createElement('dialog');
document.body.appendChild(dialogEle);
dialogEle.setAttribute('open', 'open');
var closeBtn = document.createElement('button');
closeBtn.textContent  = '关闭';
closeBtn.addEventListener('click', function() {
	dialogEle.removeAttribute('open');
});
dialogEle.appendChild(closeBtn);
dialogEle.style.cssText = 'box-shadow: 0 0 0 100vmax rgb(0,0,0,0.3); z-index: 2;';
var createDialogElement = function() {
	var dialogEle = document.createElement('dialog');
	dialogEle.setAttribute('open', 'open');
	var closeBtn = document.createElement('button');
	closeBtn.textContent  = '关闭';
	closeBtn.addEventListener('click', function() {
		dialogEle.removeAttribute('open');
	});
	dialogEle.style.cssText = 'box-shadow: 0 0 0 100vmax rgb(0,0,0,0.3); z-index: 2;';
	document.querySelectorAll('dialog').forEach(function(e) {
		e.style.zIndex = '1';
	});
	dialogEle.appendChild(closeBtn);
	return dialogEle;
}
document.body.appendChild(createDialogElement());
document.body.appendChild(createDialogElement());
document.body.appendChild(createDialogElement());
document.body.appendChild(createDialogElement());
document.body.appendChild(createDialogElement());

NeilChen4698 avatar Sep 13 '19 16:09 NeilChen4698

1

let dialog = document.createElement('dialog')
document.body.insertAdjacentElement('beforeend', dialog)

2

dialog.open = 'abc'

3

let button = document.createElement('button')
dialog.insertAdjacentElement('beforeend', button)
button.addEventListener('click', (event) => {
    dialog.close()
})

4

dialog.close()
dialog.showModal()

5

`最后使用 showModal 方法的元素会自动显示在最上层`

ghost avatar Sep 14 '19 00:09 ghost

// 1.
var dialog = document.createElement('dialog')
document.body.appendChild(dialog)
// 2.
dialog.open = true
// 3.
 var button = document.createElement('button')
button.innerText = '关闭'
dialog.appendChild(button)
button.addEventListener('click', (e) => {
    var self = e.target
    var parentDialog = self.closest('dialog')
    if (parentDialog) {
        parentDialog.close()
    }    
})
// 4.
dialog.showModal()
// 5.
var showDialog = function (dialogDom) {
    // 遍历所有dialog找到z-index最大值,加1
    var dialogList = document.querySelectorAll('dialog')
    var MaxZIndex = 99
    if (dialogList.length > 0) {
        dialogList.forEach(item => {
            var zIndex = window.getComputedStyle(item)['z-index']
            if (zIndex === 'auto') {
                item.style.zIndex = 99
            } else {
                MaxZIndex = MaxZIndex >= zIndex ? MaxZIndex : zIndex
            }
        })
    }
    dialogDom.style.zIndex = Number(MaxZIndex) + 1
    dialogDom.showModal()
}

zy017 avatar Sep 14 '19 05:09 zy017

1.
var dalog = document.createElement('dialog');
 document.body.appendChild(dalog);

2.
dalog. setAttribute('open','test')

3.
var button = document.createElement('button')
button.innerText = 'x'
dialog.appendChild(button);
button.addEventListener('click', (e) => {
   dialog.close()
})

4.
dialog.showModal(); 
 
5.
var max = 0;
var dialogArr = [];
var dalogGrou = document.getElementsByTagName('dialog');
dalogGrou.forEach(item => {
        var index = window.getComputedStyle(item)['z-index'];
        dialogArr.push(zIndex === 'auto' ? 0: index);
 })
max = Number(Math.max.apply(this,dalogGrou)) +  1;
var dalog = document.createElement('dialog');
dalog.style.zIndex = max;
 document.body.appendChild(dalog);

juzhiqiang avatar Sep 14 '19 09:09 juzhiqiang

let dialogElement = document.createElement('dialog');
document.body.append(dialogElement);
dialogElement.open = true;
let buttonElement = document.createElement('button');
buttonElement.onclick = function () {
    dialogElement.open = false;
}
dialogElement.append(buttonElement);
dialogElement.showModal();
let dialogs = document.querySelectorAll('dialog');
let maxZindex = 0;
dialogs.forEach(dialog => {
    let zIndex = getComputedStyle(dialog).zIndex;
    if (zIndex > maxZindex) {
        maxZindex = zIndex;
    }
});
dialogElement.style.zIndex = maxZindex + 1;

frankyeyq avatar Sep 14 '19 13:09 frankyeyq

    // 5
    var shouModal = HTMLDialogElement.prototype.showModal;
    HTMLDialogElement.prototype.showModal = (function () {
      var initZIndex = 1;
      return function () {
        console.log(initZIndex)
        this.style.zIndex = ++initZIndex
        shouModal.call(this)
      }
    })();
    // 1
    var dialog = document.createElement('dialog');
    document.body.append(dialog)
    // 2
    dialog.open = 'gg'
    // 3
    var button = document.createElement('button')
    button.textContent = 'close this dialog'
    dialog.append(button)
    button.onclick = function (e) {
      dialog.close()
    }

    // 4
    // 不重置open在 chrome 会报错
    dialog.open = null
    dialog.showModal()
     // test multiple dialog case
    var dialogNum = 0
    function createDialog() {
      dialogNum++
      var dialog = document.createElement('dialog');
      document.body.append(dialog)
      var button = document.createElement('button')
      button.textContent = 'close this dialog' + dialogNum
      dialog.append(button)
      dialog.showModal()
    }

les-lee avatar Sep 15 '19 16:09 les-lee

// 1
let dialog = document.createElement('dialog')
document.body.appendChild(dialog)
// 2
dialog.setAttribute('open', '打开dialog')
// 3
let button = document.createElement('button')
button.addEventListener('click', () => {
  dialog.close()
})
dialog.appendChild(button)
// 4
dialog.showModal()
// 5:通过MutationObserver监听dialog的插入,动态设置为最大z-index

可以通过::backdrop来设置遮罩的样式:

dialog::backdrop {
  background-color: rgba(0, 0, 0, 0.5);
}

xxf1996 avatar Sep 17 '19 02:09 xxf1996

HTML

  <button class="show" onclick="dialogShow()">点击显示</button>
  <button class="hidden" onclick="dialogHid()">点击隐藏</button>

CSS

    dialog {
      border: 1px black solid;
      padding: 50px 100px;
    }

    dialog::backdrop {
      background-color: rgba(48, 48, 48, .8);
      border: 0px;
    }

JS

    //点击显示
    function dialogShow() {
      let dialogDom = document.querySelector('dialog');
      dialogDom.showModal()
    }
    // 点击隐藏
    function dialogHid() {
      let dialogDom = document.querySelector('dialog');
      dialogDom.close()
    }

第一问

    // 创建元素
    let dialog = document.createElement('dialog');
    // body元素
    let body = document.querySelector('body');
    // 插入
    body.appendChild(dialog);

第二问

    let dialogDom = document.querySelector('dialog');
    dialogDom.setAttribute('open', 'true')

第三问

    let button = document.querySelector('button.hidden');
    dialogDom.appendChild(button);

第四问


  dialogShow()

第五问 1.首先遍历相加zindex肯定是不可以的,因为z-index还要看父亲的z-index的高度大小, 2.由于这个不好测试,那么我想到就是每一个dialog都是用showModal()方法打开的那么最后一个也有可能是最上面的哪一个

zengqingxiao avatar Sep 17 '19 13:09 zengqingxiao

1

 var dialog=document.createElement('dialog');
 document.body.append(dialog);

2

dialog.open=true;

3

var btn=document.createElement('button');
btn.textContent="close";
dialog.appendChild(btn);
btn.addEventListener('click',function(){
         this.parentNode.close();
    })

4

if(dialog.open){
dialog.open=false;
}
dialog.showModal()

5

想法是showModal的层级是最高的,把最后出现的dialog设置为showModal,那么如何找出最后出现的dialog

whrice avatar Sep 18 '19 12:09 whrice

    // 1.
    var dialog = document.createElement('dialog');
    document.body.appendChild(dialog);
    // 或者使用insertBefore
    // document.body.insertBefore(dialog, document.body.firstElementChild);

    // 2.
    dialog.setAttribute('open', 'abcdefg');

    // 3.
    var button = document.createElement('button');
    button.innerText = '关闭';
    button.addEventListener('click', function(){
      dialog.close();
    }, false);
    dialog.appendChild(button);

    // 4.
    // ::backdrop CSS伪元素可以用于更改dialog的背景元素样式,实现遮罩层效果
    // 不过此时要使用showModal()这个api打开dialog

    // 5
    var dialogzIndex = 1;
    // 每打开一个dialog 让dialogzIndex加一
    openBtn.addEventListener('click', function(){
      dialog.showModal();
      dialog.style.zIndex = dialogzIndex;
      dialogzIndex ++;
    }, false);
    // 每关闭一个dialog,让dialogzIndex减一
    closeBtn.addEventListener('click', function(){
      dialog.close();
      dialogzIndex --;
    }, false);

GCGligoudan avatar Sep 18 '19 14:09 GCGligoudan

//1.

var dialogDom = document.createElement("dialog");
document.body.appendChild(dialogDom);

//2.

dialogDom.setAttribute('open','')

//3.

var buttonDom = document.createElement('button');
buttonDom.textContent = '关闭';
buttonDom.addEventListener('click',function(){
    dialogDom.close()
});
dialogDom.appendChild(buttonDom);

//4.

dialogDom.showModal()
::backdrop {
    background-color: rgba(0, 0, 0, 0.5);
}

//5.

dialogDom.showModal()

kuikuiGe avatar Sep 20 '19 09:09 kuikuiGe

//第一题:

var dia = document.getElement('dialog');
document.body.appendchild(dia);

//第二题: document.getElement('dialog').open = true;

//第三题:

var button = document.getElement('button');
dialog.append(button);

//第四题: dialog.showModal();

//第五题: 没有思路

Zerwhou avatar Sep 20 '19 14:09 Zerwhou