center window.open on form submit

江枫思渺然 提交于 2019-12-02 21:37:27

问题


My code looks like this:

<script type="text/javascript">
      function directions(sacred) {
        var x = screen.width / 2 - 700 / 2;
        var y = screen.height / 2 - 450 / 2;
        window.open(sacred.action, 'Directions', 'height=485,width=700,left=' + x + ',top=' + y);
        return false;
      }
</script>

<form action="http://maps.google.com/maps" method="get" target="Directions"
      onsubmit="return directions(sacred);">

I don't understand js, so take it easy on me if it looks sloppy.

I can get this to work fine:

<form action="http://maps.google.com/maps" method="get" target="Directions"
    onsubmit="Directions=window.open('about:blank','Directions','width=600,height=400');">

Once I try to connect the onsubmit to the above script, I get lost. I don't even know if the above function is reliable.

I have popped open the hood here: jsFiddle

The problem there is the form submits into a new tab, and ignores window.open altogether.

Thank you in advance for your help.


回答1:


Try this out: http://jsfiddle.net/333Qy/1/

<script>
  function directions(sacred) {
  var x = screen.width / 2 - 700 / 2;
  var y = screen.height / 2 - 450 / 2;
  console.info(sacred);
  window.open(sacred.action, 'Directions', 'height=485,width=700,left=' + x + ',top=' + y);
  return false;
}
</script>
<p>
  <form action="http://maps.google.com/maps" method="get" target="Directions"
  onsubmit="directions(this);">
    <input class="directions-input" id="saddr" name="saddr" type="text" placeholder="enter zip-code"
    value="enter zip-code" onfocus="this.value = this.value=='enter zip-code'?'':this.value;"
    onblur="this.value = this.value==''?'enter zip-code':this.value;" />
    <input type="submit" class="directions-submit" />
    <input type="hidden" name="daddr" value="210+East+Northampton+Street,+Bath,+PA"
    />
    <input type="hidden" name="hl" value="en" />
  </form>
</p>

onsubmit should be a function call. Also, sacred is undefined. I have made the changes in the above code




回答2:


<form action="http://maps.google.com/maps" method="get" target="Directions"
      onsubmit="Directions=window.open('about:blank','Directions','width=600,height=400,left={left},top={top}'.replace('{left}', screen.width/2-700/2).replace('{top}', screen.height/2-450/2));">..</form>

I don't know why, but i does not always work.
http://jsfiddle.net/greatghoul/MCRAG/embedded/result/

Code is here.

http://jsfiddle.net/greatghoul/MCRAG/



来源:https://stackoverflow.com/questions/14207482/center-window-open-on-form-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!