Javascript: открывать и закрывать новое окно для onMouseOver & onMouseOut изображения, но только если новое окно onMouseOver = true - PullRequest
0 голосов
/ 21 июля 2011

спасибо всем за помощь мне ранее с моими проблемами Javascripting.Моя текущая проблема заключается в том, что мне нужно открыть и закрыть новое окно в onMouseOver & onMouseOut изображения, соответственно, но если новое окно onMouseOver == true, то я не хочу, чтобы новое окно закрывалось.

Я уверен, что есть простое решение, но я не могу найти способ отменить изображение onMouseOut = "closeDetails ();"если пользователь наводит курсор мыши на Новое окно.Ниже приведена большая часть кода, с которым я имею дело.Заранее спасибо за помощь.

<body>
   <img  name="img1" id="img1" onMouseOver="windowDelay(this);"
           onMouseOut="closeDetails();" src="images/127.jpg" height="240" width="166"/>
</body>

<script language="JavaScript" type="text/javascript">

// This opens the movie details pop-up after an
// half second interval.
function windowDelay(thatImg)
{
    winOpenTimer = window.setTimeout(function() {openDetails(thatImg);}, 2000);
}


// This is the function that will open the
// new window when the mouse is moved over the image
function openDetails(thatImg) 
{
    // This creates a new window and uses the hovered image name as the window 
    // name so that it can be used in the that window's javascript 
    newWindow = open("", thatImg.name,"width=400,height=500,left=410,top=210");

    // open new document 
    newWindow.document.open();


    // Text of the new document
    // Replace your " with ' or \" or your document.write statements will fail
    newWindow.document.write("<html><head><title>Movies</title>");
    newWindow.document.write("<script src='myDetails.js' type='text/javascript'>");
    newWindow.document.write("</script></head>");
    newWindow.document.write("<body bgcolor='white' onload='popUpDetails();'>");
    newWindow.document.write("... SOME OTHER HTML....");
    newWindow.document.write("</body></html>");


    // close the document
    newWindow.document.close(); 
}



// This is the function that will call the
// closeWindow() after 2 seconds
// when the mouse is moved off the image.
function closeDetails() 
{
    winCloseTimer = window.setTimeout("closeWindow();", 2000);
}

// This function closes the pop-up window
// and turns off the Window Timers
function closeWindow()
{
    // If popUpHover == true then I do not want
    // the window to close
    if(popUpHover == false)
    {
        clearInterval(winOpenTimer); 
        clearInterval(winCloseTimer);
        newWindow.close();
    }
}

function popUpDetails()
{
    // This will be used to prevent the Details Window from closing
    popUpHover = true;

    // Below is some other javascript code...
}
</script> 

1 Ответ

0 голосов
/ 21 июля 2011

Я бы не рекомендовал использовать новое окно браузера для этой задачи. Попробуйте что-то вроде этого:

var popup = {
  open = function () {
    if (this.element == null) {
      // create new div element to be our popup and store it in the popup object 
      this.element = document.createElement('div');
      this.element.id = "myPopup";
      // you don't need a full html document here. Just the stuff you were putting in the <body> tag before
      this.element.innerHTML = "<your>html</here>";
      // Some bare minimum styles to make this work as a popup. Would be better in a stylesheet
      this.element.style = "position: absolute; top: 50px; right: 50px; width: 300px; height: 300px; background-color: #fff;";
    }
    // Add it to your <body> tag
    document.body.appendChild(this.element);
    // call whatever setup functions you were calling before
    popUpDetails();
  },
  close = function () {
    // get rid of the popup
    document.body.removeChild(this.element);
    // any other code you want
  }
};

// The element you want to trigger the popup
var hoverOverMe = document.getElementById("hoverOverMe");
// set our popup open and close methods to the proper events
hoverOverMe.onmouseover = popup.open;
hoverOverMe.onmouseout = popup.close;

Это должно сделать это. Это намного проще контролировать, чем новое окно браузера. Вы захотите настроить CSS самостоятельно.

EDIT:

Вот инструкции, чтобы сделать это с реальным окном. Повторим еще раз: использование фактического окна - не лучший способ выполнить эту задачу. Стилизованный тег div, который выглядит как окно, лучше, потому что он предлагает больше контроля, а также стандартизированную функциональность в разных браузерах. Однако, если вы должны использовать окно, вот оно:

// You can use many principles from the example above, but I'll give the quick version
var popup;
var hoverOverMe = document.getElementById("hoverOverMe");

hoverOverMe.onmouseover = function () {
  popup = window.open("path_to_content", "popup");
};
hoverOverMe.onmouseout = function () {
  popup.close();
};

Работает, но не очень хорошо (ИМХО). Если у пользователя есть свои настройки, такие, что новые окна открываются в новых вкладках (как я), тогда открывается вкладка. Javascript не контролирует это. В Firefox новая вкладка откроется и получит фокус, после чего она немедленно закроется, потому что у hoverOverMe было запущено событие onmouseout (которое, очевидно, закрывает окно). Я полагаю, у вас будет такая же проблема и с реальным окном.

...