繁体   English   中英

禁用链接或阻止浏览器重定向

[英]Disable Links or Prevent Browser Redirect

小提琴 - http://liveweave.com/gWoHkb

我一直在为网页设计应用程序构建一个入门模板/演示,今天遇到了一个问题。

当我选择一个锚点时,我不希望它的 href 重定向浏览器。

我知道我可以为此使用javascript:void(0)# 'hash',但是我不想更改它的哈希值,我只是不希望它在设计时成为问题。

所以我申请了return false; 通过.on(click mousedown touchstart mouseup touchend)到它。 我注意到,当我这样做时,我对所选元素的拖动方法也设置为 return false,因此即使我的鼠标向上,它也会继续拖动。 (不应该发生)

虽然这解决了重定向问题,但也带来了更大的问题。 所以我从那个函数中删除了mouseup touchend 制作了一个新的以将以下设置为true。

$('#canvas').children().filter("a").on('click mousedown touchstart', function() {
  return false;
}).on('mouseup touchend', function() {
  return true;
});

所以我决定走一条不同的路。 When the select-tool or edit-tool is active I set all anchor's that have a target="_blank" property to target="_self" .

现在我知道如何防止重定向的唯一方法是使用 unbeforeunload ,它总是用对话框提示。

// Ask if they want to leave. 
var hook = true;
window.onbeforeunload = function() {
  if (hook) {
    return "All your stuff may not be saved. Are you sure you want to leave?"
  }
}
function unhook() {
  hook=false;
}

我不知道有什么方法可以绕过对话框并停留在页面上。

根据@duskwuff 的说法,当使用onbeforeunload要求浏览器重定向时,不允许让用户停留。

小提琴 - http://codepen.io/mikethedj4/pen/gCsih

我能想到的唯一解决方案是刷新画布。

$("#code").val($("#canvas").html());
$("#canvas").html($("#code").val());

我取了#canvas的 html 并将其设置为 textarea 的值。 然后我将该 textarea 值应用为画布的 html。

$('#canvas').children().drag("start",function( ev, dd ){
  dd.attrc = $( ev.target ).prop("className");
  dd.attrd = $( ev.target ).prop("id");
  dd.width = $( this ).width();
  dd.height = $( this ).height();
}).drag(function( ev, dd ){
  var props = {};
  if ( dd.attrc.indexOf("E") > -1 ){
    props.width = Math.max( 32, dd.width + dd.deltaX );
  }
  if ( dd.attrc.indexOf("S") > -1 ){
    props.height = Math.max( 32, dd.height + dd.deltaY );
  }
  if ( dd.attrc.indexOf("W") > -1 ){
    props.width = Math.max( 32, dd.width - dd.deltaX );
    props.left = dd.originalX + dd.width - props.width;
  }
  if ( dd.attrc.indexOf("N") > -1 ){
    props.height = Math.max( 32, dd.height - dd.deltaY );
    props.top = dd.originalY + dd.height - props.height;
  }
  if ( dd.attrd.indexOf("stylethis") > -1 ){
    props.top = dd.offsetY;
    props.left = dd.offsetX;
  }
  $('#stylethis').css( props );
}, {relative:true})
.on('dblclick', function() {
  EditableStylez();
  return false;
})
.filter("a").on('click mousedown touchstart', function() {
  return false;
}).on('mouseup touchend', function() {
  $("#code").val($("#canvas").html());
  $("#canvas").html($("#code").val());
  HandleSelectedElement();
  return false;
});

我真的很讨厌这样做,因为那里的元素越多,刷新得越多,它使用的 ram 就越多,这使得浏览器在 CPU 上运行得更加困难。

我希望有人能找到更好的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM