Подтвердить что ты не робот

Сделать атрибут title мгновенно отображаться при наведении

есть возможность сделать атрибут title тега привязки мгновенно отображаться при наведении курсора не сразу после нескольких секунд. Любое решение в JavaScript/jQuery и CSS хорошо.

4b9b3361

Ответ 1

Обработка атрибута title зависит от браузера, и для управления им не определены API-интерфейсы, которые еще меньше указаны в спецификациях. Это включает в себя задержку, продолжительность отображения, используемый шрифт, размер шрифта и т.д.

Существуют другие методы, которые можно использовать вместо атрибута title. Некоторые из них были упомянуты в других ответах. Обратите внимание, что простые "подсказки CSS" могут быть реализованы в чистом CSS довольно просто и гибко. При использовании этих методов данные, которые будут отображаться, обычно не входят в атрибут title, так как его обработка зависит от браузера, поэтому существует риск наличия вашего специального всплывающего подсказки и реализации браузера title. Хотя это возможно предотвратить последним, когда скриптинг включен, проще использовать атрибут, который не имеет эффекта по умолчанию ни на чем, например data-title=... или data-tooltip=....

Ответ 2

Один подход:

// textFrom : String, the attribute from which the text
//            should come,
// delta :    String or Number, the distance from the cursor at
//            which the tooltip should appear
function instantTooltips(textFrom, delta) {
  // if delta exists, and can be parsed to a number, we use it,
  // otherwise we use the default of 5:
  delta = parseFloat(delta) ? parseFloat(delta) : 5;

  // function to handle repositioning of the created tooltip:
  function reposition(e) {
    // get the tooltip element:
    var tooltip = this.nextSibling;
    // setting the position according to the position of the
    // pointer:
    tooltip.style.top = (e.pageY + delta) + 'px';
    tooltip.style.left = (e.pageX + delta) + 'px';
  }

  // get all elements that have an attribute from which we
  // want to get the tooltip text from:
  var toTitle = document.querySelectorAll('[' + textFrom + ']'),
    //create a span element:
    span = document.createElement('span'),
    // find if we should use textContent or innerText (IE):
    textProp = 'textContent' in document ? 'textContent' : 'innerText',
    // caching variables for use in the upcoming forEach:
    parent, spanClone;
  // adding a class-name (for CSS styling):
  span.classList.add('createdTooltip');
  // iterating over each of the elements with a title attribute:
  [].forEach.call(toTitle, function(elem) {
    // reference to the element parentNode:
    parent = elem.parentNode;
    // cloning the span, to avoid creating multiple elements:
    spanClone = span.cloneNode();
    // setting the text of the cloned span to the text
    // of the attribute from which the text should be taken:
    spanClone[textProp] = elem.getAttribute(textFrom);

    // inserting the created/cloned span into the
    // document, after the element:
    parent.insertBefore(spanClone, elem.nextSibling);

    // binding the reposition function to the mousemove
    // event:
    elem.addEventListener('mousemove', reposition);

    // we're setting textFrom attribute to an empty string
    // so that the CSS will still apply, but which
    // shouldl still not be shown by the browser:
    elem.setAttribute(textFrom, '');
  });
}

// calling the function:
instantTooltips('title', 15);
[title] {
  display: block;
  margin: 0 0 1em 0;
}

/*
  hiding, and styling, the elements we'll be creating
*/
[title] + span.createdTooltip {
  display: none;
  border: 2px solid #f90;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 0.2em 0.5em;
  border-radius: 0.75em;
}

/*
  showing the created elements on hovering the element we want to
  show tooltips for
*/
[title]:hover + span.createdTooltip {
  display: block;
  position: absolute;
}
<span title="This is the span title">A span element</span>
<img src="http://placekitten.com/g/250/250" title="A kitten." />
<input title="This is an input element title." value="This input has a title" />

Ответ 3

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

http://tech.pro/tutorial/930/jquery-custom-tooltips

Вот несколько ссылок, которые вы можете использовать

Симптом: http://craigsworks.com/projects/simpletip/

Bootstrap: http://getbootstrap.com/javascript/#tooltips

Ответ 4

Bootstraps ToolTip плагин делает довольно хорошую работу и намного более отзывчив/быстрее.

Просто требуется, чтобы файлы Bootstrap по умолчанию запускались.

CSS можно изменить в соответствии с вашими требованиями.

Более подробную информацию и примеры можно посмотреть здесь:

http://getbootstrap.com/javascript/#tooltips

Ответ 5

Вы можете скрыть тему на mouseover и добавить диапазон. затем удалите диапазон и восстановите заголовок на mouseout

$('a').hover(function(e){
    title = $(this).attr('title');
    $(this).append('<span>Im Super Fast!!!</span>')
    $(this).removeAttr('title');
},
function(e){
    $('span', this).remove();
    $(this).attr('title',title);
});

Посмотрите пример - http://jsfiddle.net/1z3catx3/1/

Примечание: вам, разумеется, потребуется стиль span

Ответ 6

лоток с помощью теневого и пограничного массива:

$('a').hover(function(e){

    title = $(this).attr('alt');
    $(this).append('<span>'+title+'</span>')


},
function(e){
    $('span', this).remove();


});

http://jsfiddle.net/1z3catx3/112/