2

我正在构建一个信息量很大的游戏屏幕,而且,即使只有第一段代码,在屏幕上显示了许多行星,我的代码也开始看起来有点混乱/复杂。

如果可能的话,我还想从查看“查看源代码”的用途中隐藏其中的一些内容,但这是次要问题。

基本上,下面的代码在屏幕上的不同绝对位置绘制 X 行星,并为每个行星提供鼠标悬停工具提示。

必须有一个“更好”和/或更有效的方法来做到这一点?基本上,我会很感激任何提示。

我担心的主要原因是 Qtip2 工具提示将变得更加复杂,页面中会添加各种玩家信息,以及一些聊天/新闻/信息框。我不想从意大利面条代码开始,当我还有主要课程要交付到页面时!

我认为我主要关心的是我将生成的大量脚本标签。以我添加到页面的每个工具提示的速率。行星图像(及其标签)的“回声”肯定是不可避免的……我真的不知道,我对此有点陌生。

<!-- File: /app/View/Games/main.ctp -->
<?php

    echo $this->Html->script('jquery-1.8.2.min');
    echo $this->Html->script('jquery.qtip');

    $game = $this->Session->read('Game');
?>
<?php
    foreach ($game['Planet'] as $planet) {
        echo $this->Html->image('../img/planet/' . $planet['planet_image_file'] .'.png', array('class' => 'planet_img planet_' . $planet['id'], 'id' => 'planet_' . $planet['id'], 'alt' => $planet['planet_name'], 'style' => 'position:absolute;top:' . $planet['y_position'] . 'px;left:' . $planet['x_position'] . 'px;'));
        echo '<script>$(\'.planet_' . $planet['id'] . '\').qtip({content: \'' . $planet['planet_name'] . '\'});</script>';
        echo '<label for="' . $planet['planet_name'] . $planet['id'] . '" style="position:absolute;top:' . ($planet['y_position'] - 20) . 'px;left:' . $planet['x_position'] . 'px;">' . $planet['planet_name'] . '</label>';
    }
?>
4

1 回答 1

2
  1. 使用样式表而不是所有那些内联样式。如果您动态添加样式,<style>则标题中始终可以有一个元素,您可以根据需要动态附加 css 定义。

  2. 使用图像精灵来帮助优化。这更适合处理背景图像,而不是内联图像,但对于它提供的性能提升,它可能是值得的。

    您将需要使用 css 图像背景的元素,而不是内联图像,但 DOM 可以同样简单。

  3. 与其调用一堆脚本来添加 qtip 东西,不如将 qtip 所需的信息作为每个元素的数据属性,并在外部 js 文件中具有一个函数,该函数循环遍历元素并基于 qtip 内容在数据属性上。

    foreach ($game['Planet'] as $planet) { echo $this->Html->image('../img/planet/' . $planet['planet_image_file'] .'.png', array('class' => 'planet_img planet_' . $planet['id'], 'id' => 'planet_' . $planet['id'], 'alt' => $planet['planet_name'], 'data-planet-name' => $planet['planet_name'])); echo '' . $planet['planet_name'] . ''; }

jQuery

$('.planet_img').each(function(){
  $(this).qtip({content: $(this).data('planet-name')});
})
于 2012-11-01T15:29:55.020 回答