如何为firefox编写event.target语句?

时间:2018-10-29 01:54:23

标签: javascript html

当用户单击外部区域时,我正在编写代码以关闭iframe。它适用于Chrome,但不适用于Firefox。我仍在努力用html和JS编写代码。

HTML:

<div id="video-iframe-div" class="v-iframe-div-off" onclick="closesubpage();">
    <iframe src="" id="video-iframe" class="v-iframe-off" name="i-video">
    </iframe>
</div>

JS:

function closesubpage() {
    var elementDiv = document.getElementById('video-iframe-div');
    var elementIframe = document.getElementById('video-iframe');
	  if (event.target != elementIframe) {
		   $('#video-iframe-div').prop('className','v-iframe-div-off');
		   $('#video-iframe').prop('className','v-iframe-off');
	  }
}

3 个答案:

答案 0 :(得分:0)

因为firefox 没有event对象飞来飞去。在chrome中,确实具有这就是为什么您的代码可在Chrome上运行的原因。

要使其适用于所有浏览器,请始终在这样的回调方法的第1个位置传递一个显式参数

function closesubpage(evt, arg1, arg2,...) {
  // 'evt' is the event object and contains the target property.
  // You can name it whatever you want, even 'event'
}

答案 1 :(得分:0)

  

我遇到了一个事实,即Firefox无法识别“ event.target”

您在哪里碰到这个?当然可以,您只需要将其作为函数参数传递即可。 https://developer.mozilla.org/en-US/docs/Web/API/Event/target

您使用的是jQuery,因此您最好在jQuery上附加一个点击处理程序,并保持代码更整洁,而不是在元素上使用onclick

$('#video-iframe-div').click(closesubpage);

然后您可以改善函数调用:

function closesubpage(event) {
    var elementIframe = $('#video-iframe');

    // If the target matches iframe, halt execution
    if (event.target === elementIframe) return;

    this.prop('className','v-iframe-div-off');
    elementIframe.prop('className','v-iframe-off');
}

答案 2 :(得分:0)

通过函数尝试内联evnt:

componentWillMount() {
    const id = this.props.location.pathname
    let axiosHome = axios.get('/home')
    let axiosUserData = axios.get("/profile/" + id)
    Promise.all(axiosHome,  axiosUserData).then(response => {
        console.log(response)
    }).catch(error => {
        console.log(error)
    })
  }
function closesubpage(event) {
console.log(event);
    // var elementDiv = document.getElementById('video-iframe-div');
    var elementIframe = document.getElementById('video-iframe');
	  if (event.target != elementIframe) {
		   $('#video-iframe-div').prop('className','v-iframe-div-off');
		   $('#video-iframe').prop('className','v-iframe-off');
	  }
}
#video-iframe-div{cursor:pointer}